WPF使用Webbrowser操作網頁的主要代碼


1,引用mshtml.dll

using mshtml;

2,獲取元素屬性值

IHTMLDocument2 doc2=(IHTMLDocument)webbrowser1.Document; IHTMLElement img=(IHTMLElement)doc2.all.item("regimg",0); string imgUrl=(string)img.getAttribute("src");

3,取表單控件

IHTMLElement loginName=(IHTMLElement)doc2.all.item("loginname",0); IHTMLElement loginPW=(IHTMLElement)doc2.all.item("password",0); IHTMLElement loingYZM=(IHTMLElement)doc2.all.item("regcode",0); IHTMLElement loginBT=(IHTMLElement)doc2.all.item("formsubmit",0);

4,填寫表單控件

loginName.setAttribute("value",tbLoginName.Text); loginPW.setAttribute("value",tbLoginPassWord.Password); loginYZM.setAttribute("value",tbYZ.Text);

5,點擊按鈕

loginBT.click();

6,執行js腳本

方法1:

IHTMLwindow win=(IHTMLWindow2)doc2.parentWindows;
win.execScript("alert('hello!')","javascript");

方法2:

webbrowser1.InvokeScript("eval","alert('hello!')");

7,屏蔽alert、confirm等,通過重定義實現

復制代碼
private voie webbrowser1_navigated(object sender,WebBroserNavigatedEventArgs e) { IHTMLWindow2 win=(IHTMLWindow2)webbrowser1.Document.Window.DomWindow; string s=@"window.alert=null; window.onerror=null;window.confirm=null; windows.open=null; window.showModalDialg=null;"; win.execScript(s,"javascript"); }
復制代碼

8,接收js消息

復制代碼
[ComVisible(true)]  //這句要加到類定義前,可與COM通信 private void webbrowser1_Navigated(objec sender,WebBrowserNavigatedEventargs e) { IHTMLWindow2 win=(IHTMLWindow2)webbrowser1.Document.Window.DomWindow; //假設把alert消息傳出來處理 string s=@"function alert(str){window.external.procMessage(str);}"; win.execScript(s,"javascript"); webbrowser1.ObjectForScripting=this; //指定腳本消息送到當前實例處理 } //處理腳本消息的方法 public void procMessage(string s) { MessageBox.Show("腳本消息:"+s); }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM