如何在Webview2中检测鼠标点击(C#/VB.NET)

3

我试图获取html元素的点击事件。我使用了一个WebBrowser:

instance = Nothing
            instance = WebBrowser1.Document
            AddHandler instance.Click, AddressOf Document_Click

但是使用Webview2,我不知道最佳实践是什么。是否需要注入JavaScript代码? 但是,如何在C#或VB.NET应用程序中获取handlder?

非常感谢。

这里提供一个示例代码。 我的函数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。

Webview Property


这个回答解决了你的问题吗?如何覆盖右键单击WebView2控件时出现的ContextMenu? - Poul Bak
您尚未添加事件处理程序(在VB.Net中)。此外,您想将 mousedown 更改为 click(所有位置 - 在VB代码和javascript中)。现在,当单击时,您应该会收到一个事件。 - Poul Bak
我猜不出来,请展示错误以及在代码中出现的位置。 - Poul Bak
刚刚注意到:您已经从结构体中注释掉了“Value” - 那么您也必须从JavaScript中注释掉“Value”。 - Poul Bak
错误是:System.NullReferenceException HResult=0x80004003 消息 = 对象引用未设置为对象的实例。我删除了注释。 我的目的是在单击元素时获取其ID或名称ID。 因此,我应该更改js代码。 - François HEBERT
显示剩余2条评论
2个回答

10

好的,我不懂VB.Net,但你似乎能够翻译C#代码,所以我会尝试使用C#创建一个简单的工作解决方案:

首先,在Nuget中下载Microsoft.Web.WebView2Newtonsoft.Json并安装到你的项目中(你可能已经做过了)。

现在将WebView2拖放到窗体上 - 然后在属性检查器中:

  1. 将源设置为:“https://google.fr/”

  2. 双击CoreWebView2InitializationCompletedWebMessageReceived事件以在您的代码中创建框架。

现在添加以下已转换为VB.Net的代码:

using Microsoft.Web.WebView2.Core;
using Newtonsoft.Json;
using System.IO;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public struct JsonObject
        {
            public string Key;
            public string Value;
        }

        private async void WebView21_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
        {
            string script = File.ReadAllText("Mouse.js");
            await webView21.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(script);
        }

        private void WebView21_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
        {
            JsonObject jsonObject = JsonConvert.DeserializeObject<JsonObject>(e.WebMessageAsJson);
            switch (jsonObject.Key)
            {
                case "click":
                    MessageBox.Show(jsonObject.Value);
                    break;

            }
        }
    }
}

现在在您的项目目录中创建一个 JavaScript 文件('Mouse.js'),选择该文件并在属性检查器中选择复制到输出目录,然后选择:仅当更改时才复制。这意味着您的 JavaScript 文件可以通过相对链接被您的 VB 程序找到。

现在将以下 JavaScript 粘贴到文件中:

document.addEventListener('click', function (event)
{
    let elem = event.target;
    let jsonObject =
    {
        Key: 'click',
        Value: elem.name || elem.id || elem.tagName || "Unkown"
    };
    window.chrome.webview.postMessage(jsonObject);
});

现在,当您运行它时,您应该会得到一个消息框,显示您单击的元素的NameIDTag Name(按照此顺序)。

我使用Key: 'click'方法的原因是,当您稍后想要检测例如MouseDown时,您可以轻松添加该键 - 然后您可以同时检测两种(否则您只能检测一种事件)。

更新:

CoreWebView2Ready事件更改为CoreWebView2InitializationCompleted。 这是事件的新名称。 它使用CoreWebView2InitializationCompletedEventArgs作为eventArgs。


谢谢,我知道这段代码。但是我忘了告诉你,它是一个WPF应用程序,而不是一个窗体应用程序。 - François HEBERT
代码不同,注意使用了 CoreWebView2Ready 事件。 - Poul Bak

1

更新新的Microsoft命名空间:

using System.Text.Json;
using System.Text.Json.Serialization;
    private void WebView_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
    {
        JsonObject jsonObject = JsonSerializer.Deserialize<JsonObject>(e.WebMessageAsJson);
        switch (jsonObject.Key)
        {
            case "click":
                MessageBox.Show(jsonObject.Value);
                break;

        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接