Hi

WebMessageReceived with navigation completed in c#

 using System;

using System.Windows.Forms;

using Microsoft.Web.WebView2.Core;


namespace WebView2Demo

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

            InitializeWebView();

        }


        async void InitializeWebView()

        {

            await webView.EnsureCoreWebView2Async(null);

            webView.CoreWebView2.WebMessageReceived += CoreWebView2_WebMessageReceived;

            webView.CoreWebView2.Settings.IsWebMessageEnabled = true;


            // Load the webpage

            webView.Source = new Uri("https://yourwebsite.com"); 


            // Inject JavaScript when page finishes loading

            webView.CoreWebView2.NavigationCompleted += (sender, args) =>

            {

                webView.CoreWebView2.ExecuteScriptAsync(@"

                    document.getElementById('idt').addEventListener('input', function() {

                        window.chrome.webview.postMessage(this.value);

                    });

                ");

            };

        }


        private void CoreWebView2_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)

        {

            string inputValue = e.WebMessageAsJson.Trim('"'); // Extract JSON value

            MessageBox.Show("Received Date: " + inputValue);

        }


        private void buttonTest_Click(object sender, EventArgs e)

        {

            // Test JavaScript messaging manually

            webView.CoreWebView2.ExecuteScriptAsync("window.chrome.webview.postMessage('Test Message');");

        }

    }

}


Previous
Next Post »