【问题标题】:How can I get the callback data with WebView2如何使用 WebView2 获取回调数据
【发布时间】:2021-07-01 05:33:28
【问题描述】:

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

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

$("#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来获取请求和响应信息,但是在回调函数中获取不到data...

在四处寻找体面之后,也许我应该使用 Javascript? JS可以捕捉到另一个函数的回调结果吗?

请给我一些建议,我是第一次使用控件...

(如果 WebView2 不能做到这一点,CefSharp 可以做到吗?)

感谢您的帮助,谢谢!

【问题讨论】:

  • 在 CefSharp 中,最简单的解决方案是从您的 JavaScript 后处理程序调用 CefSharp.PostMessage,将数据从 JavaScript 发送到您的 .Net 应用程序。 github.com/cefsharp/CefSharp/issues/2775
  • 谢谢,我会试试 CefSharp 作为另一种选择

标签: javascript c# wpf cefsharp webview2


【解决方案1】:

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

但如果您尝试获取的内容仅存在于 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 sample app 中查看更多 WebMessageReceived 和 PostWebMessage 的示例用法。

【讨论】:

  • 感谢您的解决方案,实际上我无法修改网页代码(这是另一个系统,他们不会修改任何单词..)最后我使用 AddScriptToExecuteOnDocumentCreatedAsync 注入一个 JS 监听器来监听ajaxLoadEnd 并获取服务器返回值。
猜你喜欢
  • 1970-01-01
  • 2021-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多