C#和JS交互 WebBrowser实例

时间:2022-08-30 23:05:18


本文实现了WebBrowser的简单例子

1.tian引用System.Windows.Froms.dll

2.引用WindowsFormsIntegration.dll

代码如下:

 

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Window _w = new Window();
            web_control web_c = new web_control("http://www.baidu.com");
            _w.Content = web_c;
            _w.Owner = this;
            _w.Show();
        }
    }

    public class web_control : UserControl
    {
        public System.Windows.Forms.WebBrowser _web_browser;
        public web_control(string url)
        {
            _web_browser = new System.Windows.Forms.WebBrowser();
            _web_browser.ObjectForScripting = new external_dispath(this);    
           var host = new System.Windows.Forms.Integration.WindowsFormsHost();
            host.Child = _web_browser;
            Content = host;
            Loaded += (senser, e) =>
                {
                    _web_browser.Navigate(url);
                };
        }
    }


至此,上方实现了简单的例子(除了红色那一句之外)

=========================================17.7.21更新以下========================================================

   但在后来遇到要与JS交互,在webBrowser使用过程中为了C#和JS通讯,webBrowser必须设置ObjectForScripting的属性,
它是一个object,这个object可以提供给webBrowser控件载入的网页上的script访问。(上方红色语句)

    在设置过webBrowser控件的ObjectForScripting属性后,还需要设置应用程序对com可见,不然会抛出一个异常

(ObjectForScripting 的类必须对 COM 可见。请确认该对象是公共的,或考虑向您的类添加 ComVisible 属性。),可做如下设置:


  [System.Runtime.InteropServices.ComVisibleAttribute(true)]  //使接口可见
    public class external_dispath
    {
        public web_control m_wbcontrol;
         
        public external_dispath(web_control wb_c)
        {
            m_wbcontrol = wb_c;
        }

        public Object createObject(String name)
        {
            return new external_dispath(m_wbcontrol);
        }

        public void closeWebDlg()          //为了让JS调的,作用是关闭网页弹窗
        {
            (m_wbcontrol.Parent as Window).Close();
        }
        通过在c#这一层实现external类,来达到在点击网页中右上角的关闭按钮时,关闭网页的弹窗
 }

JS代码:

  $(".close-btn").on("click",function(

e){               
 e.preventDefault();             
   TA.log({ld:'client', id:'lhb_kx_gb'});          
      try{                 
   external.closeWebDlg();      //调用外部的函数

   }catch (e){} });

最后疑问是external是哪里来的,JS和C#是怎么约定的,以后在学习JS后可能会有深好理解