[C#] Edge WebView2 與 WinForms:實現按鈕事件與本地代碼交互的指南

2024-06-12

今天來寫一篇關於 Edge WebView2 中會用到的部份,就是我在載入在 Edge WebView 2 中的網頁

我先注入 JQuery ,然後我加入按鈕事件以外,並且將該按鈕點擊事件中,傳入訊號給主體的 winform 

這樣就可以做到 call native code.


範例說明 這畫面中有三個黑色的按鈕,我會先注入 jQuery ,改變那三顆 ( class= "common-button__content") 的按鈕內容

並且加入 click 事件,點擊後讓他能夠呼叫 winform 中的 function 

1. 參考這邊文章讓你有基本的理解 並且安裝好 Edge WebView2 套件

2. 之後在  WebView21_NavigationCompleted 中加入一個事件 WebMessageReceived 其中範例就是將收到從 網頁來的訊息直接使用 

MessageBox 給呈現出來

public Form1() { InitializeComponent(); webView21.EnsureCoreWebView2Async(); webView21.CoreWebView2InitializationCompleted += WebView21_CoreWebView2InitializationCompleted; } private async void WebView21_NavigationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationCompletedEventArgs e) { //載入網頁後,在動態載入 JQuery //因為 micosoft 的 domain 有做 cros 限制 //所以只能用 https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.7.0.min.js string jqueryScript = "var script = document.createElement('script');script.src = 'https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.7.0.min.js'; document.getElementsByTagName('head')[0].appendChild(script);"; await webView21.ExecuteScriptAsync(jqueryScript); MessageBox.Show("Import JQuery Already"); webView21.WebMessageReceived += WebView21_WebMessageReceived; } private void WebView21_CoreWebView2InitializationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs e) { MessageBox.Show("Init Already"); webView21.NavigationCompleted += WebView21_NavigationCompleted; } private void WebView21_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e) { MessageBox.Show(e.TryGetWebMessageAsString()); }


3. 呼叫 jQuery 並且,讓 那三顆 ( class= "common-button__content") 的按鈕點擊後,傳送訊息到 winform 中

private void button1_Click(object sender, EventArgs e) { webView21.CoreWebView2.Navigate("https://developer.microsoft.com/zh-tw/microsoft-edge/webview2/?Wt.mc_id=DT-MVP-4030677"); } private async void btnInjectJS_Click(object sender, EventArgs e) { // 呼叫 JQuery 改變網頁資料 //並且將 class='common-button__content' 改變文字 還有加入點擊事件 //其事件為呼叫 原本 winform 中的 WebMessageReceived 並且將值傳入 var script = "$('.common-button__content').html('點我呼叫NATIVE');$('.common-button__content').click(function(){window.chrome.webview.postMessage('您好我是當麻的測試來自於網頁')});"; await webView21.ExecuteScriptAsync(script); }


結果:



reference:

https://learn.microsoft.com/zh-tw/microsoft-edge/webview2/how-to/hostobject?tabs=win32



當麻許的碎念筆記 2014 | Donma Hsu Design.