如何使用WebView2获取回调数据

4
我可以帮您进行中文翻译,以下是翻译结果:

我正在构建一个WPF应用程序,并尝试使用WebView2控件获取ajax回调数据。

Web应用程序是一个简单的登录视图,登录方法的代码如下:

$("#btn").click(function () {
            $.post("loginHandler.ashx",
                {
                    name: $("#name").val(),
                    pwd: $("#pwd").val()
                },
                function (data, status) {                   
                    var r=JSON.parse(data)
                    alert(r.result);
                });
        });

在WPF中,XAML代码如下:

<wv2:WebView2 Name="webView"  Source="http://localhost:44372/login.html" />

现在我使用 CoreWebView2_WebResourceResponseReceived 来获取请求和响应信息,但是在回调函数中无法获取数据...
在搜索了一些资料后,也许我应该使用JavaScript?JS 可以捕获另一个函数的回调结果吗?
请给我一些建议,我第一次使用这些控件...
(如果 WebView2 无法实现此功能,那么 CefSharp 可以吗?)
感谢您的帮助!

1
在CefSharp中,最简单的解决方案是从您的JavaScript后处理程序调用CefSharp.PostMessage,将数据从JavaScript发送到您的.Net应用程序。https://github.com/cefsharp/CefSharp/issues/2775 - amaitland
谢谢,我会尝试CefSharp作为另一个选择。 - walKeeper
3个回答

4

CoreWebView2.WebResourceResponseReceived 会在 WebView2 收到来自服务器的 HTTP(S) 响应时被触发,并且您可以检查响应的内容和标头。

但是,如果您要获取的内容仅存在于 JavaScript 中,则可以使用 CoreWebView2.WebMessageReceivedwindow.chrome.webview.postMessage 将内容从脚本发送到 C#。

在脚本中,您可以执行以下操作:

$("#btn").click(function () {
            $.post("loginHandler.ashx",
                {
                    name: $("#name").val(),
                    pwd: $("#pwd").val()
                },
                function (data, status) {                   
                    var r=JSON.parse(data)

                    // Send data to the host app
                    chrome.webview.postMessage(r);
                });
        });

如果您使用的是C#,您可以像这样挂接一个WebMessageReceived事件处理程序:

            // During initialization after CoreWebView2 property is set
            // and before you navigate the webview2 to the page that will
            // post the data.
            webView.CoreWebView2.WebMessageReceived += ReceiveLoginData;
            // ...
        }

        void ReceiveLoginData(object sender, CoreWebView2WebMessageReceivedEventArgs args)
        {
            String loginDataAsJson = args.WebMessageAsJson();
            // parse the JSON string into an object
            // ...
        }

您可以在WebView2示例应用程序中看到WebMessageReceived和PostWebMessage的更多使用示例。


谢谢你的解决方案,实际上我无法修改网页代码(它是另一个系统,他们不会修改任何字..)最后我使用AddScriptToExecuteOnDocumentCreatedAsync来注入一个JS监听器,以便监听ajaxLoadEnd事件并获取服务器返回值。 - walKeeper

2
在 bin/debug/ 路径下创建一个 html 文件夹:
<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="script.js"></script>

</head>
<body>
    <div id="demo">lkkkkkkkkkkkkkkkkkkkkkk</div>
    <div id="demo1">uuuuuuuuuuuuuuuuuuuuuu</div>
    <div id="demo2">pppppppppppppppppppppp</div>

    <button onclick="me()">Click me</button>
    <button onclick="sendThisItem('hidear')">Clickkkkkkkkkkkkkkkkkkk me</button>

    <script>

        function me() {
            var me = "ddddddddd";
            document.getElementById('demo1').style.color = 'yellow';
            window.chrome.webview.postMessage('dellmaddddddddddddddddddd');
        }

    </script>
    </body>
</html>

现在在 Form1.cs 中

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Microsoft.Web.WebView2.Core;
namespace WindowsFormsAppWebview
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            InitwebView();
        }

        async void InitwebView()
        {
            await webView21.EnsureCoreWebView2Async(null);
            webView21.CoreWebView2.Navigate(Path.Combine("file:", Application.StartupPath, @"html\", "index.html"));

            webView21.WebMessageReceived += webView2_WebMessageReceived;
        }
        private void webView2_WebMessageReceived(object sender, Microsoft.Web.WebView2.Core.CoreWebView2WebMessageReceivedEventArgs args)
        {
        
            label1.Text = args.TryGetWebMessageAsString();
        
        
        }

        private void button1_Click(object sender, EventArgs e)
        {
            label1.Text = "sssssssss";
            //MessageBox.Show("hello world ");
            webView21.CoreWebView2.ExecuteScriptAsync("document.getElementById('demo').style.color = 'red'");

        }

    }
}

你需要在表单中创建 label1、button1 和 webView21。

enter image description here

这行很重要:

webView21.WebMessageReceived += webView2_WebMessageReceived;


0
你可以通过生成WebView21的Event WebMessageReceived来捕获消息。
private void webView21_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
{
    string msj = e.TryGetWebMessageAsString();
    MessageBox.Show("Message:\n" + msj);
}

在点击事件中,我们需要执行下一个脚本: "window.chrome.webview.postMessage('Hi');"
private async void button1_Click(object sender, EventArgs e)
{
    //Send script to run on WebView
    //After CoreWebView2InitializationCompleted
    string  toRun = "window.chrome.webview.postMessage('Hi');";
    await webView21.ExecuteScriptAsync(script);
}

在Javascript函数中添加"window.chrome.webview.postMessage('DATA TO SEND');"是很重要的。
这是我对Melina的帖子的总结 :)

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