从 Web 浏览器控件读取 Javascript 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6876555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:11:03  来源:igfitidea点击:

Read Javascript variable from Web Browser control

c#javascriptbrowser

提问by AllStar11

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

我正在尝试读取从表单上的 WebBrowser 控件加载和调用的 Javascript 变量的值。

Example:

例子:

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

index.html 指的是一个名为“test.js”的 javascript。在 test.js 上,创建并填充了几个变量。

index.html then makes a call to this JS.

index.html 然后调用这个 JS。

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

Index.html 被加载并显示到 WebBrowser 控件中。

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?

我找到了很多关于如何调用/调用驻留在 Web 浏览器控件中的函数的帮助。如何轻松读取变量值?

回答by Juan

You could do:

你可以这样做:

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

回答by u109919

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.

您可以使用 IHTMLDocument::Script 来检索脚本引擎的自动化界面。如果您在 C# 中使用 Windows 窗体 webbrowser 控件,这意味着将 HtmlDocument.DomDocument 属性转换为 mshtml.IHTMLDocument。对于 WPF,您可以直接转换文档。

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.

全局变量作为属性添加到脚本引擎中,将全局函数作为方法添加到脚本引擎中。在 IE9 之前,如果您知道它们的名称,您可以使用 IDispatch 接口来访问这些函数/变量。HtmlDocument.InvokeScript 和 WPF 的 WebBrowser.InvokeScript 以一种很好的方式包装了它,但仅适用于 System.Reflection.BindingFlags.InvokeMethod。访问变量需要在调用Invoke时传递DISPATCH_PROPERTYGET,即在托管代码中使用BindingFlags.GetProperty。

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.

手动后期绑定并不好玩,如果您想知道后期绑定有多费力,请查看使用 Visual C# .NET 的 Office 自动化服务器绑定

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.

IE9 中存在一个问题,即无法通过 IDispatch访问变量/函数,但您仍然可以通过 IDispatchEx 以类似方式访问变量/函数。

回答by James Lawruk

To access global scope JavaScript variables, I used a custom method included here called GetGlobalVariable(). (It uses Document.InvokeScriptfrom Juan's answer. +1)

为了访问全局范围的 JavaScript 变量,我使用了此处包含的自定义方法,称为GetGlobalVariable(). (它Document.InvokeScript来自胡安的回答。+1)

Let's say your JavaScript variables created in the global scope like this:

假设您在全局范围内创建的 JavaScript 变量如下所示:

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 timerto continually check if the variables are populated.)

然后您可以GetGlobalVariable()像这样使用 C#方法访问这些值。 (您可能需要设置一个计时器来持续检查变量是否已填充。)

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.

这是GetGlobalVariable()方法。注意它检查变量引用的每个部分以避免异常。

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

回答by lazoDev

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.

我不认为您将能够从 JS 中获取变量的值,因为您的 C# 将在您的 js var 存在之前运行。我自己在获取 js 变量的值时遇到了同样的问题,但我无法直接执行此操作。您可以做的是使用 HtmlTextWriter 方法来获取值。这将允许您使用 C# 呈现的 js 调用,该调用将使您能够访问变量值。

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.

不是 100% 它会起作用,但我知道您可以通过这种方式访问​​您的 js 变量。我已经在其他项目中做到了这一点。希望这可以帮助。

回答by bfavaretto

Take a look at the HtmlWindow Class. You can get an instance of it from WebBrowser.Document.Window. If your js variables have global scope, they will belong to the Window object, and should be accessible from WebBrowser.Document.Window.DomWindowin C#.

看一看HtmlWindow 类。您可以从 WebBrowser.Document.Window. 如果您的 js 变量具有全局范围,则它们将属于 Window 对象,并且应该可以从WebBrowser.Document.Window.DomWindowC# 中访问。

回答by Rudy Lacovara

I think this is really a scoping question. If you include a file called test.js and in that file you have this line:

我认为这确实是一个范围界定问题。如果您包含一个名为 test.js 的文件,并且在该文件中包含以下行:

var myVariable;

Then that variable is created with global scope and is accessible from anywhere in your page and also in any other JavaScript files that you include. If you declare a variable like that, outside of a function, it will be created with global scope.

然后在全局范围内创建该变量,并且可以从页面中的任何位置以及您包含的任何其他 JavaScript 文件中访问该变量。如果你在函数之外声明一个这样的变量,它将在全局范围内创建。

One thought. If you're not able to access your variable in your main page then make sure that your script that declares it and assigns a value is included before the JavaScript on your page tries to use it. You could have an order of execution problem.

一念。如果您无法访问主页中的变量,请确保在页面上的 JavaScript 尝试使用它之前包含声明它并分配值的脚本。您可能遇到执行顺序问题。