c# webBrowser控件与js的交互

来源:互联网 发布:张震长相知乎 编辑:程序博客网 时间:2024/05/14 14:05

知识:

[c-sharp] view plaincopyprint?
  1. [System.Runtime.InteropServices.ComVisibleAttribute(true)] 
  2. 这是为了将该类设置为com可访问 
  3.  
  4. Url属性:WebBrowser控件显示的网页路径  
  5.  
  6. ObjectForScripting属性:该对象可由显示在WebBrowser控件中的网页所包含的脚本代码访问 
  7. JavaScript通过window.external调用C#公开的方法。即由ObjectForScripting属性设置的类的实例中所包含的公共方法。 
  8.  
  9.   
  10. // WebBrowser控件显示的网页路径 
  11. webBrowser1.Navigate(new Uri(System.Environment.CurrentDirectory + @"/XXX.html", UriKind.RelativeOrAbsolute)); 
  12. // 将当前类设置为可由脚本访问 
  13. webBrowser1.ObjectForScripting = this

.CS

[c-sharp] view plaincopyprint?
  1. using System; 
  2. using System.Collections.Generic; 
  3. using System.Linq; 
  4. using System.Text; 
  5. using System.Windows; 
  6. using System.Windows.Controls; 
  7. using System.Windows.Data; 
  8. using System.Windows.Documents; 
  9. using System.Windows.Input; 
  10. using System.Windows.Media; 
  11. using System.Windows.Media.Imaging; 
  12. using System.Windows.Navigation; 
  13. using System.Windows.Shapes; 
  14. using System.Web; 
  15. using System.Security.Permissions; 
  16. namespace WpfApplication1 
  17.     /// <summary> 
  18.     /// Interaction logic for Window1.xaml 
  19.     /// </summary> 
  20.     public partialclass Window1 : Window 
  21.     { 
  22.         public Window1() 
  23.         { 
  24.             InitializeComponent(); 
  25.             Basic ds = new Basic (); 
  26.             webBrowser1.Navigate(new Uri(System.Environment.CurrentDirectory + @"/aaa.html", UriKind.RelativeOrAbsolute));//获取根目录的日历文件 
  27.             webBrowser1.ObjectForScripting = ds;//该对象可由显示在WebBrowser控件中的网页所包含的脚本代码访问 
  28.         } 
  29.         privatevoid Button_Click(object sender, RoutedEventArgs e) 
  30.         { 
  31.             textBox1.Text = DoSomething.name; 
  32.         } 
  33.  
  34.     } 
  35.     [System.Runtime.InteropServices.ComVisibleAttribute(true)]//将该类设置为com可访问 
  36.     publicclass Basic 
  37.     { 
  38.         publicstaticstring name; 
  39.         publicstring Name 
  40.         { 
  41.             get {return name; } 
  42.             set { name = value; } 
  43.         } 
  44.         publicvoid ClickEvent(string str) 
  45.         { 
  46.             this.Name = str; 
  47.         } 
  48.     } 

HTML

[c-sharp] view plaincopyprint?
  1. <HTML> 
  2. <head> 
  3. <mce:script language="JavaScript" type="text/javascript"><!-- 
  4. function Selec() 
  5. var divV=document.getElementById('div2').innerText; 
  6. window.external.ClickEvent(divV); 
  7. // --></mce:script> 
  8. </head> 
  9. <Body> 
  10. <Form> 
  11. <div id="div1" onClick="Selec();">000000000000</div> 
  12. <div id="div2">111111</div> 
  13. </Form> 
  14. </Body> 
  15. </HTML> 

如果需要在运行时点击按钮后再将值传入页面显示,则用下列方法传值

this.webBrowser1.InvokeScript("js中的函数",“要传的值”);

原创粉丝点击