wpf CoreWebView2_WebMessageReceived未被触发

gk7wooem  于 2023-05-01  发布在  其他
关注(0)|答案(1)|浏览(371)

我有一个Angular Web应用程序,有一个简单的按钮和一个文本框。此应用程序将由WPF用户控件中包含的WebView2控件加载。
我期待着发送一个JSON字符串的文本框文本后,单击按钮。此JSON字符串将作为消息发布到WebView2,从而由用户控件进一步处理。但是,未在用户控件类内触发事件“WebMessageReceived”的事件处理程序。
这里是所有的代码:Angular :处理程序。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);
  }

用户控件类:已编辑

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);
}
pdkcd3nj

pdkcd3nj1#

在上面的例子中,当你应该调用window.chrome.webview.postMessage时,你调用了window.chrome.postMessage。有关详细信息,请参阅window.postMessage VS window.chrome.webview.postMessage和WebView2 postMessage文档。

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

相关问题