Search code examples
c#angularwpfuser-controlswebview2

CoreWebView2_WebMessageReceived not getting triggered


I have an Angular web app with a simple button and a text box. This app will be loaded by the WebView2 control contained in a WPF user control.

I'm looking to send a JSON string for the text box text upon clicking the button. This JSON string will be posted as a message to the WebView2 and thus to be further processed by the user control. However, event handler for the event 'WebMessageReceived' is not getting triggered inside the user control class.

here are all the codes: Angular: Handler.js:

exports.SendMessageToParent=function (jsonObject){
    console.log("function called");
    window.parent.postMessage(jsonObject,'*');
    window.parent.close();
}

app.component.ts:

import { Component, OnInit } from '@angular/core';
import {SendMessageToParent} from '../app/Handlers.js';

  OnClick(){
  console.log(this.webtext)
  const JSONData = {Key1: this.webtext};
  const jsonObject = JSON.stringify(JSONData);
  
  SendMessageToParent(jsonObject);
  }

User control class: EDITED

private async void Initialize()
{
            webView2.CoreWebView2InitializationCompleted += 
                                WebView2_CoreWebView2InitializationCompleted;
    await webView2.EnsureCoreWebView2Async();
    

}

private async void WebView2_CoreWebView2InitializationCompleted(object? sender, CoreWebView2InitializationCompletedEventArgs e)
{
    if(e.IsSuccess)
    {
        webView2.CoreWebView2.Navigate("http://localhost:4200/");
        await webView2.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(
            "window.addEventListener('message', event => 
            {window.chrome.postMessage(event.data);})"
            );
        webView2.CoreWebView2.WebMessageReceived += CoreWebView2_WebMessageReceived;
    }
}

private void CoreWebView2_WebMessageReceived(object? sender, CoreWebView2WebMessageReceivedEventArgs e)
{
    // Deserialize JSON data
    var data = JsonSerializer.Deserialize<string>(e.WebMessageAsJson);

    // Raise event with incoming data
    WebDataReceived?.Invoke(this, data);
}

Solution

  • In the above you are calling window.chrome.postMessage when you should be calling window.chrome.webview.postMessage. See window.postMessage VS window.chrome.webview.postMessage and WebView2 postMessage docs for more information.

            await webView2.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(
                "window.addEventListener('message', event => 
                {window.chrome.webview.postMessage(event.data);})"
                );