[Winform-WebBrowser]-在html頁面中js調用winForm類方法


   在winform項目中嵌入了網頁,想通過html頁面調用后台方法,如何實現呢?其實很簡單,主要有三部:

 

1、在被調用方法類上加上[ComVisible(true)]標簽,意思就是當前類可以com組件的形式供外包調用

2、在webBrowser控件中設置可被html頁面調用的類即:webBrowser1.ObjectForScripting = this;前端即可通過window.external訪問this對象

3、html頁面調用后台方法:window.external.方法名(); 此處的window.external相當於webBrowser1.ObjectForScripting

 

 1    //ComVisible 設置對外的可訪問性,在html中可使用 js 訪問成員方法
 2     [ComVisible(true)]
 3     public partial class Form1 : Form
 4     {
 5         public Form1()
 6         {
 7             InitializeComponent();
 8         }
 9 
10         private void Form1_Load(object sender, EventArgs e)
11         {
12             //browser.Url = new Uri("https://www.baidu.com");
13             browser.Url = new Uri("http://localhost:3133/index.html");
14             browser.ObjectForScripting = this;
15         }
16 
17         private void btnSearch_Click(object sender, EventArgs e)
18         {
19             HtmlElement kw = browser.Document.All["kw"];
20             HtmlElement btn = browser.Document.All["su"];
21 
22             string txt = txtwd.Text.Trim();
23             kw.SetAttribute("value", txt);
24             btn.InvokeMember("click");
25         }
26 
27         private void btnDo_Click(object sender, EventArgs e)
28         {
29             int[] arr = { 1, 23 };
30             browser.Document.InvokeScript("f",new object[] { "{1,2,3}" });
31         }
32 
33         public void WinF(string arg)
34         {
35             MessageBox.Show(arg);
36         }
37     }

html 代碼:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <meta charset="utf-8" />
</head>
<body>
    <h1>Hello World!</h1>

    <button onclick="ext()">external</button>
    
    <script>    
        
        var f = function (msg) {
            //if()
            alert(Object.prototype.toString.call(msg));
        }
        //調用winform 中的方法
        function ext() {
            //調用winform 中的方法
            window.external.WinF("hello");
        }
    
    </script>


</body>
</html>

 


免責聲明!

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



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