C# WebBrowser高级应用

 

 

通过注入脚本实现查看选中内容HTML源代码的功能【目前似乎只有遨游支持此功能,调试页面时很轻盈好用的功能】

1 private void MainForm_Load( object sender, EventArgs e)
2 {
3 wbMain.ObjectForScripting = this ;
4 wbMain.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wbMain_DocumentCompleted);
5 }
6
7 void wbMain_DocumentCompleted( object sender, WebBrowserDocumentCompletedEventArgs e)
8 {
9 InjectGetSelection();
10 }
11
12 private void InjectGetSelection()
13 {
14 string js = " function kai_GetSelect(){return document.selection.createRange().htmlText;} " ;
15 // js += " function kai_Delete(){var ele = document.getElementById('jsInject'); ele.parentNode.removeChild(ele);} ";
16   InjectJS(js);
17 }
18
19 private void InjectJS( string js)
20 {
21 var ele = wbMain.Document.CreateElement( " script " );
22 ele.SetAttribute( " text " , js);
23 ele.Id = " jsInject " ;
24 wbMain.Document.Body.AppendChild(ele);
25 }
26
27 private void btnViewSelected_Click( object sender, EventArgs e)
28 {
29 if (wbMain.Document == null )
30 return ;
31
32 object obj = wbMain.Document.InvokeScript( " kai_GetSelect " );
33 if (obj != null )
34 txtHtml.Text = obj.ToString();
35 else
36 txtHtml.Text = "" ;
37 // wbMain.Document.InvokeScript("kai_Delete");
38   }

 

你可能感兴趣的:(WebBrowser)