簡體   English   中英

如何使用 WebView2 獲取回調數據

[英]How can I get the callback data with 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.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 的示例用法。

在 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'");

        }

    }
}

您需要在 Form 中創建 label1,button1, webView21。

在此處輸入圖像描述

這一行很重要:

webView21.WebMessageReceived += webView2_WebMessageReceived;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM