How to inject Javascript in WebBrowser control?

前端 未结 15 2307
夕颜
夕颜 2020-11-22 04:56

I\'ve tried this:

string newScript = textBox1.Text;
HtmlElement head = browserCtrl.Document.GetElementsByTagName(\"head\")[0];
HtmlElement scriptEl = browser         


        
15条回答
  •  旧时难觅i
    2020-11-22 05:32

    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.

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

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

    Step 3) Add this VB.Net code above your "Public Class Form1" line:

    Step 4) Add a WebBrowser control to your project

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

    Step 6) Add this VB.Net sub which will inject a function "CallbackGetVar" into the web page's 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:

    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:

    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.

提交回复
热议问题