How to inject Javascript in WebBrowser control?

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

I\'ve tried this:

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


        
相关标签:
15条回答
  • 2020-11-22 05:28

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

    0 讨论(0)
  • 2020-11-22 05:28

    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 this helps.

    0 讨论(0)
  • 2020-11-22 05:31

    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:

    [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:

    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");
                }
            }
        }
    }
    
    0 讨论(0)
  • 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:
    <System.Runtime.InteropServices.ComVisibleAttribute(True)>

    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.

    0 讨论(0)
  • 2020-11-22 05:33
    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)

    Edit: Fixed case issue in function set.

    0 讨论(0)
  • 2020-11-22 05:34

    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.

    0 讨论(0)
提交回复
热议问题