javascript - 如何使用 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 可以这样做吗?)
感谢您提供任何帮助,谢谢!
解决方案
每当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 的示例用法。
推荐阅读
- angular - Angular 不想从另一个表中检索数据
- php - 使用 Web 服务器时,用于存储来自 php 函数的照片的文件夹的正确路径是什么?
- javascript - 如何在角度 9 中使用 print.js 打印多个 PDF
- javascript - 赛普拉斯:test runner一旦测试失败就停止,即使中途测试失败,我们还能继续测试吗?
- symfony - 如何禁用 Symfony 5 类缓存以进行本地调试?
- selenium - 在 selenium 中具有多个条件的软断言
- sql - 简单的 SQL 数据透视
- python - Selenium Webdriver 和 Jupyter Notebook。find_elements_by_xpath 不在同一个单元格中工作
- python - 将数据框对象转换为 int64 时出错
- elasticsearch - 在 Linux 上增加 Elastic Search 的磁盘分配