How to inject Javascript in WebBrowser control?

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

    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:

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

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

    3) Get a reference to your script element's 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:

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

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

    Hth, Richard

提交回复
热议问题