c# winform程式在WebBrowser控制元件中執行javascript指令碼
阿新 • • 發佈:2019-01-01
來自:http://outofmemory.cn/code-snippet/1706/c-winform-program-WebBrowser-control-execution-javascript-script
winform的WebBrowser控制元件,可以方便的載入頁面並執行一些操作,我們可以注入自己的js指令碼在頁面中執行,方法如下:
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");
另外如果你的指令碼非常簡單也可以用下面的方法:
string jCode = "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[] { jCode });
Enjoy Coding!!!