How to inject Javascript in WebBrowser control?

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

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

    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.

提交回复
热议问题