在AxWebBrowser控制元件注入JS指令碼的方法
阿新 • • 發佈:2018-11-19
- 通過new建立 AxWebBrowser
AxSHDocVw.AxWebBrowser webBrowser = new AxSHDocVw.AxWebBrowser();
2 新增載後的完成事件DocumentComplete
webBrowser.DocumentComplete += WebBrowser_DocumentComplete;
3 .加入當前頁面的Controls
this.toolStripContainer.ContentPanel.Controls.Add(webBrowser);
4獲取HTMLDocument元素,通過axWebBrowser1.Document元素直接獲取再轉換
5 通過execScript的方法新增js指令碼
/// <summary> /// WebBrowser 載入完成後事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void axWebBrowser1_DocumentComplete(object sender, AxSHDocVw.DWebBrowserEvents2_DocumentCompleteEvent e) { this.axWebBrowser1.DocumentComplete -= axWebBrowser1_DocumentComplete; string jsString = @"function T(){ var ele = window.document.getElementById('kw'); if (ele != null && ele != undefined) { ele.setAttribute('value', '測試JS指令碼注入AxWebBrowser'); } } T()"; mshtml.IHTMLWindow2 win = ((mshtml.HTMLDocumentClass)this.axWebBrowser1.Document).parentWindow; win.execScript(jsString, "Javascript");