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;
doc.InvokeScript(
"Update_UI_From_Values();");

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;
win.execScript(
"Update_UI_From_Values();", "javascript");

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

Filed under:

Comments

# Phillip Pearson said:

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

doc.InvokeScript("Update_UI_From_Values");

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

Sunday, August 12, 2007 5:45 AM
# John said:

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?

Tuesday, April 1, 2008 5:51 PM
# samir said:

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!!!

Monday, August 3, 2009 1:11 AM
# Fraser said:

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.

F.

Monday, August 31, 2009 6:05 AM