简体   繁体   中英

Disable Javascript click events in C# WebBrowser

Intro:
I'm working on a C# WinForms + WebBrowser project.
I'd like to do some processing upon a click on a hyperlink.

Here's how I hook a click event to every hyperlink in an HTML document:

void webBrowser_DocumentCompleted( object sender, WebBrowserDocumentCompletedEventArgs e )
{
    HtmlElementCollection links = webBrowser.Document.Links;
    foreach ( HtmlElement link in links )
    {
      link.Click += delegate { MessageBox.Show( "C# Click!" ); };
    }
}

The Problem:
The above code works well, but the problem is that I get side effects from javascript code which also performs some clicking action.

I learned the hard way that this problem comes in many shapes and forms..
Here's a not so obvious example of a jQuery action that makes life harder:

 $(document).ready(function() { $("a").click(function() { alert("jQuery Click;"); }); });
 <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>> </head> <body> <a href="#">Click Me!</a> </body> </html> <html> <body>

What happens here is that when clicking a hyperlink in the WebBrowser control - the "jQuery Click," alert will pop up first. and only after dismissing it will the "C# Click!" message be shown.

The Question:
I've searched far and wide, but didn't yet come up with an answer.

How could IC#-programmatically prevent jQuery or any other form of javascript code from being executed in the WebBrowser?

Clarification:
I'd like to say I already tried to alter the document in many ways, eg stripping <script> tags from webBrowser.DocumentText , and from the inner html node, and by working with HtmlElement and the underlying IHtmlElement objects...

But no luck..

Changing the webBrowser.DocumentText causes the document to get reloaded from a string, and thus I lose any credentials (eg cookie) I had to the original site. And changing IHtmlElement objects doesn't really make a difference 'cause the jQuery script was already loaded so, again, I am unable to prevent the event from occurring.

To my knowledge there is no way to disable JavaScript execution in WebBrowser component. The only you can do is to suppress the error messages with ScriptErrorsSupressed property set to false. An idea would be to pre-filter your HTML and eliminate all your "onclick" events from HTML using regular expressions before you render your HTML in the WebBrowser component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM