77 lines
2.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace AIProofread
{
[ClassInterface(ClassInterfaceType.AutoDual)]
[ComVisible(true)]
public class Bridge
{
public static Bridge bridge = new Bridge();
private static readonly Dictionary<string, WebView2> webViewDict = new Dictionary<string, WebView2>();
public void showDialog(string message)
{
System.Windows.Forms.MessageBox.Show(message);
}
// 获取文档所有文本数据
public string getAllText()
{
return Tools.GetAllText();
}
public void noticeOtherWeb(string json, string targetWebName)
{
if (targetWebName != null)
{
if (webViewDict.ContainsKey(targetWebName))
{
SendMessageToWeb(webViewDict[targetWebName], json);
}
}
else
{
// 如果没有指定 则向所有 webview 发送消息
foreach (var item in webViewDict)
{
SendMessageToWeb(item.Value, json);
}
}
}
private void SendMessageToWeb(WebView2 webView, string json)
{
webView.CoreWebView2.PostWebMessageAsJson(json);
}
public async static void InitWebEnvAsync(string name, WebView2 webView)
{
webView.Name = name;
if (webViewDict.ContainsKey(webView.Name))
{
webViewDict[name] = webView;
}
else
{
webViewDict.Add(name, webView);
}
// 禁用web安全允许跨域 否则需要web编译为umd加载模式
var ops = new CoreWebView2EnvironmentOptions("--disable-web-security");
var env = await CoreWebView2Environment.CreateAsync(null, Config.WEB_DATA_PATH, ops);
await webView.EnsureCoreWebView2Async(env);
//webView.CoreWebView2.Settings.AreDevToolsEnabled = false;
//webView.CoreWebView2.Settings.AreDefaultScriptDialogsEnabled = false;
//webView.CoreWebView2.Settings.AreHostObjectsAllowed = true;
// 添加 js与客户端代理
webView.CoreWebView2.AddHostObjectToScript("bridge", bridge);
}
}
}