如何在WebBrowser控件中注入Javascript ?

时间:2022-06-07 20:44:51

I've tried this:

我已经试过这个:

string newScript = textBox1.Text;
HtmlElement head = browserCtrl.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = browserCtrl.Document.CreateElement("script");
lblStatus.Text = scriptEl.GetType().ToString();
scriptEl.SetAttribute("type", "text/javascript");
head.AppendChild(scriptEl);
scriptEl.InnerHtml = "function sayHello() { alert('hello') }";

scriptEl.InnerHtml and scriptEl.InnerText both give errors:

scriptEl。InnerHtml,scriptEl。InnerText都给实现错误:

System.NotSupportedException: Property is not supported on this type of HtmlElement.
   at System.Windows.Forms.HtmlElement.set_InnerHtml(String value)
   at SForceApp.Form1.button1_Click(Object sender, EventArgs e) in d:\jsight\installs\SForceApp\SForceApp\Form1.cs:line 31
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

Is there an easy way to inject a script into the dom?

是否有一种简单的方法将脚本注入dom?

14 个解决方案

#1


89  

For some reason Richard's solution didn't work on my end (insertAdjacentText failed with an exception). This however seems to work:

由于某些原因,Richard的解决方案并没有在我的结束(insert邻接文本以一个异常失败)结束。然而,这似乎起了作用:

HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = "function sayHello() { alert('hello') }";
head.AppendChild(scriptEl);
webBrowser1.Document.InvokeScript("sayHello");

This answer explains how to get the IHTMLScriptElement interface into your project.

这个答案解释了如何将IHTMLScriptElement接口引入到您的项目中。

#2


41  

HtmlDocument doc = browser.Document;
HtmlElement head = doc.GetElementsByTagName("head")[0];
HtmlElement s = doc.CreateElement("script");
s.SetAttribute("text","function sayHello() { alert('hello'); }");
head.AppendChild(s);
browser.Document.InvokeScript("sayHello");

(tested in .NET 4 / Windows Forms App)

(在。net 4 / Windows窗体应用程序中测试)

Edit: Fixed case issue in function set.

编辑:功能集中的固定案例问题。

#3


24  

Here is the easiest way that I found after working on this:

这是我在这之后发现的最简单的方法:

string javascript = "alert('Hello');";
// or any combination of your JavaScript commands
// (including function calls, variables... etc)

// WebBrowser webBrowser1 is what you are using for your web browser
webBrowser1.Document.InvokeScript("eval", new object[] { javascript });

What global JavaScript function eval(str) does is parses and executes whatever is written in str. Check w3schools ref here.

全局JavaScript函数eval(str)所做的是解析和执行在str中写的任何东西。

#4


21  

Also, in .NET 4 this is even easier if you use the dynamic keyword:

同样,在。net 4中,如果你使用动态关键字:

dynamic document = this.browser.Document;
dynamic head = document.GetElementsByTagName("head")[0];
dynamic scriptEl = document.CreateElement("script");
scriptEl.text = ...;
head.AppendChild(scriptEl);

#5


17  

If all you really want is to run javascript, this would be easiest (VB .Net):

如果您真正想要的是运行javascript,这将是最简单的(VB .Net):

MyWebBrowser.Navigate("javascript:function foo(){alert('hello');}foo();")

I guess that this wouldn't "inject" it but it'll run your function, if that's what you're after. (Just in case you've over-complicated the problem.) And if you can figure out how to inject in javascript, put that into the body of the function "foo" and let the javascript do the injection for you.

我想这不会“注入”它,但它会运行你的函数,如果这是你想要的。(以防你把问题弄得太复杂了。)如果你能想出如何注入javascript,把它放到函数的“foo”的主体中,让javascript为你做注入。

#6


9  

The managed wrapper for the HTML document doesn't completely implement the functionality you need, so you need to dip into the MSHTML API to accomplish what you want:

HTML文档的托管包装器并没有完全实现所需的功能,因此您需要使用MSHTML API来实现您想要的功能:

1) Add a reference to MSHTML, which will probalby be called "Microsoft HTML Object Library" under COM references.

1)添加对MSHTML的引用,这将在COM引用下被称为“Microsoft HTML对象库”。

2) Add 'using mshtml;' to your namespaces.

2)将“使用mshtml”添加到名称空间中。

3) Get a reference to your script element's IHTMLElement:

3)获取对脚本元素的IHTMLElement的引用:

IHTMLElement iScriptEl = (IHTMLElement)scriptEl.DomElement;

4) Call the insertAdjacentText method, with the first parameter value of "afterBegin". All the possible values are listed here:

4)调用insert邻接文本方法,第一个参数值为“afterBegin”。所有可能的值都列在这里:

iScriptEl.insertAdjacentText("afterBegin", "function sayHello() { alert('hello') }");

5) Now you'll be able to see the code in the scriptEl.InnerText property.

现在你可以在scriptEl中看到代码了。InnerText属性实现。

Hth, Richard

Hth,理查德

#7


7  

this is a solution using mshtml

这是一个使用mshtml的解决方案。

IHTMLDocument2 doc = new HTMLDocumentClass();
doc.write(new object[] { File.ReadAllText(filePath) });
doc.close();

IHTMLElement head = (IHTMLElement)((IHTMLElementCollection)doc.all.tags("head")).item(null, 0);
IHTMLScriptElement scriptObject = (IHTMLScriptElement)doc.createElement("script");
scriptObject.type = @"text/javascript";
scriptObject.text = @"function btn1_OnClick(str){
    alert('you clicked' + str);
}";
((HTMLHeadElementClass)head).appendChild((IHTMLDOMNode)scriptObject);

#8


7  

I believe the most simple method to inject Javascript in a WebBrowser Control HTML Document from c# is to invoke the "execStrip" method with the code to be injected as argument.

我认为在WebBrowser控件HTML文档中注入Javascript最简单的方法是调用“execStrip”方法,将代码注入为参数。

In this example the javascript code is injected and executed at global scope:

在这个例子中,javascript代码在全局范围内被注入和执行:

var jsCode="alert('hello world from injected code');";
WebBrowser.Document.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" });

If you want to delay execution, inject functions and call them after:

如果您想要延迟执行,请注入函数并在之后调用它们:

var jsCode="function greet(msg){alert(msg);};";
WebBrowser.Document.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" });
...............
WebBrowser.Document.InvokeScript("greet",new object[] {"hello world"});

This is valid for Windows Forms and WPF WebBrowser controls.

这对于Windows窗体和WPF WebBrowser控件是有效的。

This solution is not cross browser because "execScript" is defined only in IE and Chrome. But the question is about Microsoft WebBrowser controls and IE is the only one supported.

这个解决方案不是跨浏览器的,因为“execScript”只在IE和Chrome中定义。但问题是关于微软的WebBrowser控件,IE是唯一支持的。

For a valid cross browser method to inject javascript code, create a Function object with the new Keyword. This example creates an anonymous function with injected code and executes it (javascript implements closures and the function has access to global space without local variable pollution).

对于一个有效的跨浏览器方法来注入javascript代码,用新的关键字创建一个函数对象。这个示例创建一个带有注入代码的匿名函数并执行它(javascript实现闭包,函数可以访问全局空间,而不需要局部变量污染)。

var jsCode="alert('hello world');";
(new Function(code))();

Of course, you can delay execution:

当然,您可以延迟执行:

var jsCode="alert('hello world');";
var inserted=new Function(code);
.................
inserted();

Hope it helps

希望它能帮助

#9


7  

As a follow-up to the accepted answer, this is a minimal definition of the IHTMLScriptElement interface which does not require to include additional type libraries:

作为被接受的答案的后续,这是IHTMLScriptElement接口的最小定义,它不需要包含额外的类型库:

[ComImport, ComVisible(true), Guid(@"3050f28b-98b5-11cf-bb82-00aa00bdce0b")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
[TypeLibType(TypeLibTypeFlags.FDispatchable)]
public interface IHTMLScriptElement
{
    [DispId(1006)]
    string text { set; [return: MarshalAs(UnmanagedType.BStr)] get; }
}

So a full code inside a WebBrowser control derived class would look like:

因此,WebBrowser控件派生类中的完整代码应该是:

protected override void OnDocumentCompleted(
    WebBrowserDocumentCompletedEventArgs e)
{
    base.OnDocumentCompleted(e);

    // Disable text selection.
    var doc = Document;
    if (doc != null)
    {
        var heads = doc.GetElementsByTagName(@"head");
        if (heads.Count > 0)
        {
            var scriptEl = doc.CreateElement(@"script");
            if (scriptEl != null)
            {
                var element = (IHTMLScriptElement)scriptEl.DomElement;
                element.text =
                    @"function disableSelection()
                    { 
                        document.body.onselectstart=function(){ return false; }; 
                        document.body.ondragstart=function() { return false; };
                    }";
                heads[0].AppendChild(scriptEl);
                doc.InvokeScript(@"disableSelection");
            }
        }
    }
}

#10


2  

I used this :D

我用这个:D

HtmlElement script = this.WebNavegador.Document.CreateElement("SCRIPT");
script.SetAttribute("TEXT", "function GetNameFromBrowser() {" + 
"return 'My name is David';" + 
"}");

this.WebNavegador.Document.Body.AppendChild(script);

Then you can execute and get the result with:

然后你可以执行并得到结果:

string myNameIs = (string)this.WebNavegador.Document.InvokeScript("GetNameFromBrowser");

I hope to be helpful

我希望能有所帮助。

#11


1  

You can always use a "DocumentStream" or "DocumentText" property. For working with HTML documents I recommend a HTML Agility Pack.

您可以始终使用“DocumentStream”或“DocumentText”属性。为了处理HTML文档,我推荐一个HTML敏捷包。

#12


1  

Here is a VB.Net example if you are trying to retrieve the value of a variable from within a page loaded in a WebBrowser control.

这是一个VB。Net示例,如果您试图从web浏览器控件中加载的页面中检索变量的值。

Step 1) Add a COM reference in your project to Microsoft HTML Object Library

步骤1)在您的项目中添加COM引用到Microsoft HTML对象库。

Step 2) Next, add this VB.Net code to your Form1 to import the mshtml library:
Imports mshtml

下一步,添加这个VB。导入mshtml库的Form1的网络代码:导入mshtml。

Step 3) Add this VB.Net code above your "Public Class Form1" line:
<System.Runtime.InteropServices.ComVisibleAttribute(True)>

步骤3)添加这个VB。在您的“公共类Form1”行之上的网络代码:< system . runtime.interopservice . comvisibleattribute (True)>。

Step 4) Add a WebBrowser control to your project

步骤4)为您的项目添加一个WebBrowser控件。

Step 5) Add this VB.Net code to your Form1_Load function:
WebBrowser1.ObjectForScripting = Me

步骤5)添加这个VB。您的Form1_Load函数的网络代码:WebBrowser1。ObjectForScripting =我

Step 6) Add this VB.Net sub which will inject a function "CallbackGetVar" into the web page's Javascript:

步骤6)添加这个VB。将一个函数“CallbackGetVar”注入到web页面的Javascript中:

    Public Sub InjectCallbackGetVar(ByRef wb As WebBrowser)
        Dim head As HtmlElement
        Dim script As HtmlElement
        Dim domElement As IHTMLScriptElement

        head = wb.Document.GetElementsByTagName("head")(0)
        script = wb.Document.CreateElement("script")
        domElement = script.DomElement
        domElement.type = "text/javascript"
        domElement.text = "function CallbackGetVar(myVar) { window.external.Callback_GetVar(eval(myVar)); }"
        head.AppendChild(script)
    End Sub

Step 7) Add the following VB.Net sub which the Javascript will then look for when invoked:

步骤7)添加以下VB。当被调用时,Javascript将查找的网子:

    Public Sub Callback_GetVar(ByVal vVar As String)
        Debug.Print(vVar)
    End Sub

Step 8) Finally, to invoke the Javascript callback, add this VB.Net code when a button is pressed, or wherever you like:

最后,要调用Javascript回调,添加这个VB。当按下按钮时,或你喜欢的地方:

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        WebBrowser1.Document.InvokeScript("CallbackGetVar", New Object() {"NameOfVarToRetrieve"})
    End Sub

Step 9) If it surprises you that this works, you may want to read up on the Javascript "eval" function, used in Step 6, which is what makes this possible. It will take a string and determine whether a variable exists with that name and, if so, returns the value of that variable.

步骤9)如果它让您感到意外,您可能想要读一下在步骤6中使用的Javascript“eval”函数,这使它成为可能。它将使用一个字符串并确定是否有一个变量与该名称存在,如果是,则返回该变量的值。

#13


0  

What you want to do is use Page.RegisterStartupScript(key, script) :

你要做的是使用页面。RegisterStartupScript(关键、脚本):

See here for more details: http://msdn.microsoft.com/en-us/library/aa478975.aspx

参见这里了解更多细节:http://msdn.microsoft.com/en-us/library/aa478975.aspx。

What you basically do is build your javascript string, pass it to that method and give it a unique id( in case you try to register it twice on a page.)

您主要做的是构建javascript字符串,将其传递给该方法,并赋予它一个惟一的id(以防您试图在页面上注册两次)。

EDIT: This is what you call trigger happy. Feel free to down it. :)

编辑:这就是你所说的“触发快乐”。你放心吧。:)

#14


0  

If you need to inject a whole file then you can use this:

如果你需要注入一个完整的文件,你可以使用这个:

With Browser.Document'    
   'Dim Head As HtmlElement = .GetElementsByTagName("head")(0)'
   'Dim Script As HtmlElement = .CreateElement("script")'
   'Dim Streamer As New StreamReader(<Here goes path to file as String>)'
   'Using Streamer'
       'Script.SetAttribute("text", Streamer.ReadToEnd())'
   'End Using'
   'Head.AppendChild(Script)'
   '.InvokeScript(<Here goes a method name as String and without parentheses>)'
'End With'

Remember to import System.IO in order to use the StreamReader. I hope it's help you

记得要导入系统。IO为了使用StreamReader。我希望它对你有帮助。

#1


89  

For some reason Richard's solution didn't work on my end (insertAdjacentText failed with an exception). This however seems to work:

由于某些原因,Richard的解决方案并没有在我的结束(insert邻接文本以一个异常失败)结束。然而,这似乎起了作用:

HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = "function sayHello() { alert('hello') }";
head.AppendChild(scriptEl);
webBrowser1.Document.InvokeScript("sayHello");

This answer explains how to get the IHTMLScriptElement interface into your project.

这个答案解释了如何将IHTMLScriptElement接口引入到您的项目中。

#2


41  

HtmlDocument doc = browser.Document;
HtmlElement head = doc.GetElementsByTagName("head")[0];
HtmlElement s = doc.CreateElement("script");
s.SetAttribute("text","function sayHello() { alert('hello'); }");
head.AppendChild(s);
browser.Document.InvokeScript("sayHello");

(tested in .NET 4 / Windows Forms App)

(在。net 4 / Windows窗体应用程序中测试)

Edit: Fixed case issue in function set.

编辑:功能集中的固定案例问题。

#3


24  

Here is the easiest way that I found after working on this:

这是我在这之后发现的最简单的方法:

string javascript = "alert('Hello');";
// or any combination of your JavaScript commands
// (including function calls, variables... etc)

// WebBrowser webBrowser1 is what you are using for your web browser
webBrowser1.Document.InvokeScript("eval", new object[] { javascript });

What global JavaScript function eval(str) does is parses and executes whatever is written in str. Check w3schools ref here.

全局JavaScript函数eval(str)所做的是解析和执行在str中写的任何东西。

#4


21  

Also, in .NET 4 this is even easier if you use the dynamic keyword:

同样,在。net 4中,如果你使用动态关键字:

dynamic document = this.browser.Document;
dynamic head = document.GetElementsByTagName("head")[0];
dynamic scriptEl = document.CreateElement("script");
scriptEl.text = ...;
head.AppendChild(scriptEl);

#5


17  

If all you really want is to run javascript, this would be easiest (VB .Net):

如果您真正想要的是运行javascript,这将是最简单的(VB .Net):

MyWebBrowser.Navigate("javascript:function foo(){alert('hello');}foo();")

I guess that this wouldn't "inject" it but it'll run your function, if that's what you're after. (Just in case you've over-complicated the problem.) And if you can figure out how to inject in javascript, put that into the body of the function "foo" and let the javascript do the injection for you.

我想这不会“注入”它,但它会运行你的函数,如果这是你想要的。(以防你把问题弄得太复杂了。)如果你能想出如何注入javascript,把它放到函数的“foo”的主体中,让javascript为你做注入。

#6


9  

The managed wrapper for the HTML document doesn't completely implement the functionality you need, so you need to dip into the MSHTML API to accomplish what you want:

HTML文档的托管包装器并没有完全实现所需的功能,因此您需要使用MSHTML API来实现您想要的功能:

1) Add a reference to MSHTML, which will probalby be called "Microsoft HTML Object Library" under COM references.

1)添加对MSHTML的引用,这将在COM引用下被称为“Microsoft HTML对象库”。

2) Add 'using mshtml;' to your namespaces.

2)将“使用mshtml”添加到名称空间中。

3) Get a reference to your script element's IHTMLElement:

3)获取对脚本元素的IHTMLElement的引用:

IHTMLElement iScriptEl = (IHTMLElement)scriptEl.DomElement;

4) Call the insertAdjacentText method, with the first parameter value of "afterBegin". All the possible values are listed here:

4)调用insert邻接文本方法,第一个参数值为“afterBegin”。所有可能的值都列在这里:

iScriptEl.insertAdjacentText("afterBegin", "function sayHello() { alert('hello') }");

5) Now you'll be able to see the code in the scriptEl.InnerText property.

现在你可以在scriptEl中看到代码了。InnerText属性实现。

Hth, Richard

Hth,理查德

#7


7  

this is a solution using mshtml

这是一个使用mshtml的解决方案。

IHTMLDocument2 doc = new HTMLDocumentClass();
doc.write(new object[] { File.ReadAllText(filePath) });
doc.close();

IHTMLElement head = (IHTMLElement)((IHTMLElementCollection)doc.all.tags("head")).item(null, 0);
IHTMLScriptElement scriptObject = (IHTMLScriptElement)doc.createElement("script");
scriptObject.type = @"text/javascript";
scriptObject.text = @"function btn1_OnClick(str){
    alert('you clicked' + str);
}";
((HTMLHeadElementClass)head).appendChild((IHTMLDOMNode)scriptObject);

#8


7  

I believe the most simple method to inject Javascript in a WebBrowser Control HTML Document from c# is to invoke the "execStrip" method with the code to be injected as argument.

我认为在WebBrowser控件HTML文档中注入Javascript最简单的方法是调用“execStrip”方法,将代码注入为参数。

In this example the javascript code is injected and executed at global scope:

在这个例子中,javascript代码在全局范围内被注入和执行:

var jsCode="alert('hello world from injected code');";
WebBrowser.Document.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" });

If you want to delay execution, inject functions and call them after:

如果您想要延迟执行,请注入函数并在之后调用它们:

var jsCode="function greet(msg){alert(msg);};";
WebBrowser.Document.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" });
...............
WebBrowser.Document.InvokeScript("greet",new object[] {"hello world"});

This is valid for Windows Forms and WPF WebBrowser controls.

这对于Windows窗体和WPF WebBrowser控件是有效的。

This solution is not cross browser because "execScript" is defined only in IE and Chrome. But the question is about Microsoft WebBrowser controls and IE is the only one supported.

这个解决方案不是跨浏览器的,因为“execScript”只在IE和Chrome中定义。但问题是关于微软的WebBrowser控件,IE是唯一支持的。

For a valid cross browser method to inject javascript code, create a Function object with the new Keyword. This example creates an anonymous function with injected code and executes it (javascript implements closures and the function has access to global space without local variable pollution).

对于一个有效的跨浏览器方法来注入javascript代码,用新的关键字创建一个函数对象。这个示例创建一个带有注入代码的匿名函数并执行它(javascript实现闭包,函数可以访问全局空间,而不需要局部变量污染)。

var jsCode="alert('hello world');";
(new Function(code))();

Of course, you can delay execution:

当然,您可以延迟执行:

var jsCode="alert('hello world');";
var inserted=new Function(code);
.................
inserted();

Hope it helps

希望它能帮助

#9


7  

As a follow-up to the accepted answer, this is a minimal definition of the IHTMLScriptElement interface which does not require to include additional type libraries:

作为被接受的答案的后续,这是IHTMLScriptElement接口的最小定义,它不需要包含额外的类型库:

[ComImport, ComVisible(true), Guid(@"3050f28b-98b5-11cf-bb82-00aa00bdce0b")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
[TypeLibType(TypeLibTypeFlags.FDispatchable)]
public interface IHTMLScriptElement
{
    [DispId(1006)]
    string text { set; [return: MarshalAs(UnmanagedType.BStr)] get; }
}

So a full code inside a WebBrowser control derived class would look like:

因此,WebBrowser控件派生类中的完整代码应该是:

protected override void OnDocumentCompleted(
    WebBrowserDocumentCompletedEventArgs e)
{
    base.OnDocumentCompleted(e);

    // Disable text selection.
    var doc = Document;
    if (doc != null)
    {
        var heads = doc.GetElementsByTagName(@"head");
        if (heads.Count > 0)
        {
            var scriptEl = doc.CreateElement(@"script");
            if (scriptEl != null)
            {
                var element = (IHTMLScriptElement)scriptEl.DomElement;
                element.text =
                    @"function disableSelection()
                    { 
                        document.body.onselectstart=function(){ return false; }; 
                        document.body.ondragstart=function() { return false; };
                    }";
                heads[0].AppendChild(scriptEl);
                doc.InvokeScript(@"disableSelection");
            }
        }
    }
}

#10


2  

I used this :D

我用这个:D

HtmlElement script = this.WebNavegador.Document.CreateElement("SCRIPT");
script.SetAttribute("TEXT", "function GetNameFromBrowser() {" + 
"return 'My name is David';" + 
"}");

this.WebNavegador.Document.Body.AppendChild(script);

Then you can execute and get the result with:

然后你可以执行并得到结果:

string myNameIs = (string)this.WebNavegador.Document.InvokeScript("GetNameFromBrowser");

I hope to be helpful

我希望能有所帮助。

#11


1  

You can always use a "DocumentStream" or "DocumentText" property. For working with HTML documents I recommend a HTML Agility Pack.

您可以始终使用“DocumentStream”或“DocumentText”属性。为了处理HTML文档,我推荐一个HTML敏捷包。

#12


1  

Here is a VB.Net example if you are trying to retrieve the value of a variable from within a page loaded in a WebBrowser control.

这是一个VB。Net示例,如果您试图从web浏览器控件中加载的页面中检索变量的值。

Step 1) Add a COM reference in your project to Microsoft HTML Object Library

步骤1)在您的项目中添加COM引用到Microsoft HTML对象库。

Step 2) Next, add this VB.Net code to your Form1 to import the mshtml library:
Imports mshtml

下一步,添加这个VB。导入mshtml库的Form1的网络代码:导入mshtml。

Step 3) Add this VB.Net code above your "Public Class Form1" line:
<System.Runtime.InteropServices.ComVisibleAttribute(True)>

步骤3)添加这个VB。在您的“公共类Form1”行之上的网络代码:< system . runtime.interopservice . comvisibleattribute (True)>。

Step 4) Add a WebBrowser control to your project

步骤4)为您的项目添加一个WebBrowser控件。

Step 5) Add this VB.Net code to your Form1_Load function:
WebBrowser1.ObjectForScripting = Me

步骤5)添加这个VB。您的Form1_Load函数的网络代码:WebBrowser1。ObjectForScripting =我

Step 6) Add this VB.Net sub which will inject a function "CallbackGetVar" into the web page's Javascript:

步骤6)添加这个VB。将一个函数“CallbackGetVar”注入到web页面的Javascript中:

    Public Sub InjectCallbackGetVar(ByRef wb As WebBrowser)
        Dim head As HtmlElement
        Dim script As HtmlElement
        Dim domElement As IHTMLScriptElement

        head = wb.Document.GetElementsByTagName("head")(0)
        script = wb.Document.CreateElement("script")
        domElement = script.DomElement
        domElement.type = "text/javascript"
        domElement.text = "function CallbackGetVar(myVar) { window.external.Callback_GetVar(eval(myVar)); }"
        head.AppendChild(script)
    End Sub

Step 7) Add the following VB.Net sub which the Javascript will then look for when invoked:

步骤7)添加以下VB。当被调用时,Javascript将查找的网子:

    Public Sub Callback_GetVar(ByVal vVar As String)
        Debug.Print(vVar)
    End Sub

Step 8) Finally, to invoke the Javascript callback, add this VB.Net code when a button is pressed, or wherever you like:

最后,要调用Javascript回调,添加这个VB。当按下按钮时,或你喜欢的地方:

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        WebBrowser1.Document.InvokeScript("CallbackGetVar", New Object() {"NameOfVarToRetrieve"})
    End Sub

Step 9) If it surprises you that this works, you may want to read up on the Javascript "eval" function, used in Step 6, which is what makes this possible. It will take a string and determine whether a variable exists with that name and, if so, returns the value of that variable.

步骤9)如果它让您感到意外,您可能想要读一下在步骤6中使用的Javascript“eval”函数,这使它成为可能。它将使用一个字符串并确定是否有一个变量与该名称存在,如果是,则返回该变量的值。

#13


0  

What you want to do is use Page.RegisterStartupScript(key, script) :

你要做的是使用页面。RegisterStartupScript(关键、脚本):

See here for more details: http://msdn.microsoft.com/en-us/library/aa478975.aspx

参见这里了解更多细节:http://msdn.microsoft.com/en-us/library/aa478975.aspx。

What you basically do is build your javascript string, pass it to that method and give it a unique id( in case you try to register it twice on a page.)

您主要做的是构建javascript字符串,将其传递给该方法,并赋予它一个惟一的id(以防您试图在页面上注册两次)。

EDIT: This is what you call trigger happy. Feel free to down it. :)

编辑:这就是你所说的“触发快乐”。你放心吧。:)

#14


0  

If you need to inject a whole file then you can use this:

如果你需要注入一个完整的文件,你可以使用这个:

With Browser.Document'    
   'Dim Head As HtmlElement = .GetElementsByTagName("head")(0)'
   'Dim Script As HtmlElement = .CreateElement("script")'
   'Dim Streamer As New StreamReader(<Here goes path to file as String>)'
   'Using Streamer'
       'Script.SetAttribute("text", Streamer.ReadToEnd())'
   'End Using'
   'Head.AppendChild(Script)'
   '.InvokeScript(<Here goes a method name as String and without parentheses>)'
'End With'

Remember to import System.IO in order to use the StreamReader. I hope it's help you

记得要导入系统。IO为了使用StreamReader。我希望它对你有帮助。