首页 > 解决方案 > 如何使用 WebView2 获取回调数据

问题描述

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

WebApplication 是一个简单的登录视图,登录方法代码如下:

$("#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 可以这样做吗?)

感谢您提供任何帮助,谢谢!

标签: javascriptc#wpfcefsharpwebview2

解决方案


每当WebView2从服务器获得 http(s) 响应时,就会引发 CoreWebView2.WebResourceResponseReceived,您可以检查响应的内容和标头。

但是,如果您尝试获取的内容仅存在于 JavaScript 中,您可以使用CoreWebView2.WebMessageReceived并将window.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 的示例用法。


推荐阅读