webbrowser 裏的js函數和C#的函數互相調用方式

1.c#程序裏要添加  [System.Runtime.InteropServices.ComVisibleAttribute(true)] 和  webBrowser1.ObjectForScripting = this;javascript

位置:html

   
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    public partial class Form1 : Form
    {      
        public Form1()
        {
            InitializeComponent();
            refresh();
            string path1 = System.Windows.Forms.Application.StartupPath + @"\" + "PlanMngPage" + @"\home.htm";
            webBrowser1.Navigate(new Uri(path1));
            webBrowser1.ObjectForScripting = this;
        }
 public void MyMessageBox(string message)
        {
            MessageBox.Show(message);
        }

java

 

2.在JS使用 window.external.引用的窗體的函數();   來引用C#裏的函數web

  eg:c#

  <body  onload="window.external.MyMessageBox('javascript訪問C#代碼')">

函數

 

出處:https://blog.csdn.net/gsch_12/article/details/52224454this

 

再給出一個在C#中調用JS的方法spa

  private void button1_Click_1(object sender, EventArgs e)
        {

            if (webBrowser1.Document.GetElementById("a") != null)
            {
                HtmlElement element = webBrowser1.Document.GetElementById("a");
                element.SetAttribute("value", textBox1.Text);
                //textBox1.Text = element.GetAttribute("value");
            }


            webBrowser1.Document.InvokeScript("tt", new object[] { "頂一個" });

        }

html代碼:.net

<body>
    <input type="text" id="a" />
    <br />
    <input type="button" id="btn" value="test" onclick="tt('haha')" />
    <br />
    <input type="button" id="btn" value="test C#" onclick="Run('--C#')" />
</body>

<script>
    function tt(obj) {
        alert("hello:" + obj);
    }
</script>
<script type="text/javascript" charset="utf-8">
    function Run(str) {
        window.external.ShowMsg(str);
        //alert(str);
    }
</script>
相關文章
相關標籤/搜索