我尝试获取 html 元素的事件点击。使用我使用的 WebBrowser:
instance = Nothing
instance = WebBrowser1.Document
AddHandler instance.Click, AddressOf Document_Click
但是对于 Webview2,我没有找到好的做法。我必须注入一个javascript代码吗?但是,我如何在 C# 或 Vb.net 应用程序中获取处理程序?
非常感谢。
这里有一个示例代码。我的函数中没有返回:WebView1_WebMessageReceived。为什么 ?我想,我忘记了什么……
Imports System.IO
Imports Microsoft.Web.WebView2.Core
Imports Newtonsoft.Json
Class MainWindow
Public Sub New()
InitializeComponent()
InitializeSyncroComponent()
' Ajoutez une initialisation quelconque après l'appel InitializeComponent().
End Sub
Structure JsonObject
Public Key As String
'Public Value As PointF
End Structure
Async Sub InitializeSyncroComponent()
Await webview1.EnsureCoreWebView2Async
webview1.CoreWebView2.Navigate("https://google.fr/")
End Sub
Private Sub WebView1_WebMessageReceived(ByVal sender As Object, ByVal e As Microsoft.Web.WebView2.Core.CoreWebView2WebMessageReceivedEventArgs)
Dim jsonObject As JsonObject = JsonConvert.DeserializeObject(Of JsonObject)(e.WebMessageAsJson)
Select Case jsonObject.Key
Case "contextmenu"
'contextMenuStrip1.Show(Point.Truncate(jsonObject.Value))
Case "mousedown"
Stop
' contextMenuStrip1.Hide()
End Select
End Sub
Private Sub webview1_NavigationCompleted(sender As Object, e As CoreWebView2NavigationCompletedEventArgs) Handles webview1.NavigationCompleted
webview1.CoreWebView2.Settings.AreDefaultContextMenusEnabled = False
Dim script As String = File.ReadAllText("d:\test_mouse.js")
webview1.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(script)
End Sub
End Class
脚本Java:
document.addEventListener('mousedown', function (event)
{
let jsonObject =
{
Key: 'mousedown',
Value:
{
X: event.screenX,
Y: event.screenY
}
};
window.chrome.webview.postMessage(jsonObject);
});
编辑:我发现我的错误......真的不多!
我忘记了 webview 属性中 WebMessageReceived 的声明。