3

I'm building a WPF application and try to get the ajax callback data with the WebView2 control.

WebApplication is a simple Login View, and login method code like this:

$("#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:

<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...

After searching around for decent maybe I should use Javascript? Can JS catch another function's callback result?

Please give me some advise, I'm the first time use to controls...

(If WebView2 can't do this, may the CefSharp do that?)

Any assistance is appreciated, THX!

amaitland
  • 4,073
  • 3
  • 25
  • 63
walKeeper
  • 31
  • 1
  • 4
  • 1
    In CefSharp the easiest solution would be to call CefSharp.PostMessage from your JavaScript post handler sending the data from JavaScript to your .Net application. https://github.com/cefsharp/CefSharp/issues/2775 – amaitland Jul 01 '21 at 07:46
  • Thanks, I'll try the CefSharp as another choice – walKeeper Jul 02 '21 at 08:04

2 Answers2

3

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.

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#.

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:

            // 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.

David Risney
  • 3,886
  • 15
  • 16
  • Thanks for your solution, in fact I can't modify the web code(it's another system and they won't modify any word..) Finally I use AddScriptToExecuteOnDocumentCreatedAsync to inject a JS Listener to listen the ajaxLoadEnd and get the server return value. – walKeeper Jul 02 '21 at 08:06
1

Create a html folder in bin/debug/ path :

<!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

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.

enter image description here

This line is importent:

webView21.WebMessageReceived += webView2_WebMessageReceived;

melina
  • 195
  • 1
  • 8