WebBrowser control and InvokeScript

This is a little code nugget I planned to blog about a while ago, but forgot, so my recap and reasoning is not a 100% but hopefully it might be of help to someone struggelig with making the System.Windows.Forms.WebBrowser control execute scripts programatically.

I started out using the WebBrowser.InvokeScript method to force execution of clientside scripts in the page that was loaded in my WebBrowser control:

HtmlWindow win = doc.Window;

This is where my reasoning is not complete (because i didn't bother to actually reproduce the original problem..), but basically it didn't work as expected. After some Reflector action I figured out that the mshtml.IHTMLWindow2.execScript method wasn't actually directly mapped into the new WebBrowser APIs and I figured I'd give it a go and add a reference to Microsoft.mshtml.dll (COM component Microsoft HTML Object Library):

mshtml.IHTMLWindow2 win = (mshtml.IHTMLWindow2)propertyEditorWebBrowser.Document.Window.DomWindow;
"Update_UI_From_Values();", "javascript");

This had the desired effect and the script executed. Too bad the managed option didn't do the job.


  • At least in C# 2005 Express, the following works:


    The parameter is just a function name... perhaps the "();" after it was what was breaking it for you.

  • I have been running into problems using InvokeScript to return the array from a JavaScript function. Works fine for a single string though.

    Any help?

  • Is there a way to pass the parameters while calling execScript Method such as win.execScript("Update_UI_From_Values(number1, number2,number3);", "javascript"); as I have to pass three values from C# variables to Javascript function. I do appreciate your help!!!

  • Hi,

    object result = doc.InvokeScript("myfunction", new object[] { "arg1", 2, "etc" });

    calls 'myfunction' in the page passing the parameters "arg1", 2, "etc"
    the 'result' object will have the same value as the result of the active scripting call.


Comments have been disabled for this content.