简体   繁体   English

如何使用 WebView2 获取回调数据

[英]How can I get the callback data with WebView2

I'm building a WPF application and try to get the ajax callback data with the WebView2 control.我正在构建一个 WPF 应用程序并尝试使用 WebView2 控件获取 ajax 回调数据。

WebApplication is a simple Login View, and login method code like this: WebApplication 是一个简单的登录视图,登录方法代码如下:

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

the XAML code in wpf is: wpf 中的 XAML 代码是:

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

Now I use the CoreWebView2_WebResourceResponseReceived to get the request and response information, but I can't get the data in the callback function...现在我使用CoreWebView2_WebResourceResponseReceived来获取请求和响应信息,但是在回调函数中获取不到数据...

After searching around for decent maybe I should use Javascript?在四处寻找体面之后,也许我应该使用 Javascript? Can JS catch another function's callback result? JS 可以捕捉到另一个函数的回调结果吗?

Please give me some advise, I'm the first time use to controls...请给我一些建议,我是第一次使用控件...

(If WebView2 can't do this, may the CefSharp do that?) (如果 WebView2 不能这样做,CefSharp 可以这样做吗?)

Any assistance is appreciated, THX!感谢您提供任何帮助,谢谢!

CoreWebView2.WebResourceResponseReceived is raised whenever the WebView2 gets an http(s) response back from a server and you can check the contents and headers for the response.每当WebView2从服务器获得 http(s) 响应时,就会引发 CoreWebView2.WebResourceResponseReceived,您可以检查响应的内容和标头。

But if the content you're trying to obtain exists only in JavaScript you can use CoreWebView2.WebMessageReceived and window.chrome.webview.postMessage to send the content from script to your C#.但是,如果您尝试获取的内容仅存在于 JavaScript 中,您可以使用CoreWebView2.WebMessageReceivedwindow.chrome.webview.postMessage将内容从脚本发送到您的 C#。

In script you'd do something along the lines of:在脚本中,您将执行以下操作:

$("#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);
                });
        });

And in your C# you'd hook up a WebMessageReceived event handler something like:在您的 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
            // ...
        }

You can see more example usage of WebMessageReceived and PostWebMessage in the WebView2 sample app .您可以在WebView2 示例应用程序中看到更多 WebMessageReceived 和 PostWebMessage 的示例用法。

Create a html folder in bin/debug/ path :在 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>

Now in Form1.cs现在在 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'");

        }

    }
}

You need to Create label1,button1 , webView21 in Form.您需要在 Form 中创建 label1,button1, webView21。

在此处输入图像描述

This line is importent:这一行很重要:

webView21.WebMessageReceived += webView2_WebMessageReceived; webView21.WebMessageReceived += webView2_WebMessageReceived;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM