Read Javascript variable from Web Browser control

后端 未结 6 748
攒了一身酷
攒了一身酷 2020-12-01 19:04

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 javas

6条回答
  •  生来不讨喜
    2020-12-01 19:24

    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;
    }
    

提交回复
热议问题