To access global scope JavaScript variables, I used a custom method included here called GetGlobalVariable()
. (It uses Document.InvokeScript
from Juan's answer. +1)
Let's say your JavaScript variables created in the global scope like this:
var foo = "bar";
var person = {};
var person.name = "Bob";
Then you can access these values using the C# GetGlobalVariable()
method like so. (You may need to set up a timer to continually check if the variables are populated.)
var foo = GetGlobalVariable(webBrowser, "foo");
var name = GetGlobalVariable(webBrowser, "person.name");
Here is the GetGlobalVariable()
method. Notice it checks each part of variable reference to avoid an exception.
private object GetGlobalVariable(WebBrowser browser, string variable)
{
string[] variablePath = variable.Split('.');
int i = 0;
object result = null;
string variableName = "window";
while (i < variablePath.Length)
{
variableName = variableName + "." + variablePath[i];
result = browser.Document.InvokeScript("eval", new object[] { variableName });
if (result == null)
{
return result;
}
i++;
}
return result;
}