How to detect Javascript execution in WebBrowser control

Gabber picture Gabber · Mar 5, 2012 · Viewed 10.8k times · Source

I have a WebBrowser control in my C# application. The web browser is under the user's control, that is, he can load any web page his computer can access on the web (of course limited by proxy, hosts file and so on).

I need to know and to be notified when there is a Javascript call inside the page loaded in the web browser component.

First example: given a link like this

<a href="javascript:void(0)" onclick="jsFunct();">test</a>

When the user clicks the link I need to know that the function "jsFunct" has been called.

Second example: given a call like

<script type="text/javascript">
    window.setTimeout("jsFunct()", 1000);
</script>

I need to know that, 1 second after the execution of the script, the function jsFunct has been called.

The best thing would be to have an event fired when the function is called. It would also be great if the event could get the Javascript code executed, or at least the function name in the arguments.

EDIT:

Even if the question is related to the webbrowser component, anything that allows the user to detect javascript activation (even via js) would be fine, being able to inject a js that handles the javascript event and passes it to the wb control triggering some event that it can handle.

Answer

Krishna picture Krishna · Mar 16, 2012

On the webbrowser load event,

  1. Inject Jquery
  2. Inject Monitor scripts

,

private void addScript(HtmlElement head, string scriptSource) 
{ 
HtmlElement lhe_script = head.Document.CreateElement("script"); 
IHTMLScriptElement script = (IHTMLScriptElement)lhe_script.DomElement; 
script.src = scriptSource;
head.AppendChild(lhe_script);            
} 

addScript(Webbrowser.Head, @"<Change File Path here>jquery.min.js");
addScript(WebBrowser.Head, @"InjectMonitor.js");

your file InjectMonitor.js should be something like this

 $(document).ready(function () { 
        //Add click event for every anchor on the page loaded- note this merely alerts text on click. you can however add your own function
        $("a").click(function (e) { alert($(this).text()); return false;}) 
    });