John
John

Reputation: 785

Vb.net - capturing click event in webview2 control

I'm trying to capture a click event in a webview2 control and I can't seem to get it to function.

Webview2 is initialised and renders the HTML as desired, and I've added a handler for webmessage received...

 AddHandler Webview2.WebMessageReceived, AddressOf Webview2_WebMessageReceived

This is just attempting to throw a messagebox for now...

Private Async Sub Webview2_WebMessageReceived(sender As Object, e As CoreWebView2WebMessageReceivedEventArgs)
    MessageBox.Show(e.TryGetWebMessageAsString)
End Sub

Within the HTML being rendered i've got a button with id="butt1".

In the webview2's navigation completed event, I'm firing this to listen for the click...

 Await Webview2.ExecuteScriptAsync("document.getElementsById('butt1').click();")

Everything runs without exception, yet the messagebox is never fired on button click.

Can anyone nudge me in the right direction here?

Upvotes: 0

Views: 554

Answers (1)

alexb
alexb

Reputation: 33

Your event handler for Click has to create a Json object with the info you want to send and then call window.chrome.webview.postMessage(jsonObject); This object will be received in your WebMessageReceived() handler where you will have to decode it and act upon the info it contains.
I would place all the js code in a file and, at run time, read it into a string and call AddScriptToExecuteOnDocumentCreatedAsync(jsCode) from within CoreWebView2InitializationCompleted.

Upvotes: 0

Related Questions