Read Javascript variable from Web Browser control

I am trying to read the value of a Javascript variable which is loaded and called from a WebBrowser control on my form.

Example:

index.html refers to a javascript called 'test.js' On test.js, several variables are created and populated.

index.html then makes a call to this JS.

Index.html is loaded and displayed into the WebBrowser control.

I've found lots of help on how to call/invoke functions that reside in the web browser control. How how can I easily read a variable value?


You could do:

Document.InvokeScript("eval", new object[] { "my_var_name" });

You can use IHTMLDocument::Script to retrieve the automation interface of the script engine. If you use the Windows Forms webbrowser control in C#, this means casting the HtmlDocument.DomDocument property to mshtml.IHTMLDocument. For WPF you cast the document directly.

Global variables are added to the script engine as properties and global functions as methods. Until IE9, you can use the IDispatch interface to access those functions/variables if you know their names. HtmlDocument.InvokeScript and WPF's WebBrowser.InvokeScript wraps this up in a nice way, but only for System.Reflection.BindingFlags.InvokeMethod. For accessing variables you need to pass DISPATCH_PROPERTYGET when you call Invoke, that is, use BindingFlags.GetProperty in managed code.

Manual late binding is not fun, In case you want to know how laborious late binding is, check Binding for Office automation servers with Visual C# .NET.

There is a problem in IE9 that the variables/functions are not accessible via IDispatch, but you can still access variables/functions via IDispatchEx in a similar way.


I do no think that you are going to be able to just get the value of your variable from your JS because your C# is going to run before your js var even exist. I have had this same issue myself with getting values of my js variables and I have not been able to do it directly. What you can do is use an HtmlTextWriter method to get the values. This will allow you to use a C# rendered js call that will give you access to your variable values.

For Example:

 protected override void RenderContents(HtmlTextWriter writer)
    {
        EnsureChildControls();
        base.RenderContents(writer);

writer.BeginRender();
        writer.RenderBeginTag(HtmlTextWriterTag.Script);
        writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript");

        writer.Write("myJavaScriptVar = (\" + myC#Var + \")"); 
writer.RenderEndTag();

Not 100% that it will work, but I know that you can access your js variables this way. I have done this with other projects. Hope this helps.