I try to get the events click of html element. With a WebBrowser I used :
instance = Nothing
instance = WebBrowser1.Document
AddHandler instance.Click, AddressOf Document_Click
But with Webview2 I don't find the good practice. I must inject a javascript code ? But, how I get the handlder in C# or Vb.net application ?
Thanks a lot.
Here a sample code. I don't have the return in my function : WebView1_WebMessageReceived. Why ? I think, I forgot something....
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
Script Java:
document.addEventListener('mousedown', function (event)
{
let jsonObject =
{
Key: 'mousedown',
Value:
{
X: event.screenX,
Y: event.screenY
}
};
window.chrome.webview.postMessage(jsonObject);
});
Edit: I found my error... it was really not much !
I had forgot the déclaration of the WebMessageReceived in the webview property.