How to inject Javascript in WebBrowser control?

前端 未结 15 2525
夕颜
夕颜 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:53

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

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

    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.

    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.

    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).

    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

提交回复
热议问题