Last active
March 18, 2022 13:44
-
-
Save DanielBaumert/dc259754c169de5c4aaa481988518284 to your computer and use it in GitHub Desktop.
WebView2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// WebView2 - My Setup | |
internal partial class MainForm : Form | |
// [...] | |
protected override async void OnLoad(EventArgs e) | |
{ | |
base.OnLoad(e); | |
var webView2Environment = await CoreWebView2Environment.CreateAsync(); | |
await UI.EnsureCoreWebView2Async(webView2Environment); | |
UI.CoreWebView2.WebMessageReceived += UI_WebMessageReceived; | |
UI.CoreWebView2.Settings.AreHostObjectsAllowed = true; | |
UI.CoreWebView2.Settings.AreDefaultContextMenusEnabled = false; | |
UI.CoreWebView2.Settings.AreDefaultScriptDialogsEnabled = false; | |
UI.CoreWebView2.OpenDevToolsWindow(); | |
// Load | |
//string pageContent = WebRessourceLoader.load(); | |
UI.CoreWebView2.Navigate("file:///" + Path.GetFullPath("www/index.html").Replace("\\", "/")); // single page | |
// load WebMessageHandler | |
JsObjectLoader.Load(UI.CoreWebView2); | |
LoacWebLayerV1(); | |
} | |
private void UI_WebMessageReceived(object? sender, CoreWebView2WebMessageReceivedEventArgs e) | |
{ | |
var jsonMessage = e.TryGetWebMessageAsString(); // always a JSON string | |
if (string.IsNullOrEmpty(jsonMessage)) | |
{ | |
return; | |
} | |
WebMessageManager.WebMessageHandle(jsonMessage); | |
} | |
} | |
// [...] | |
internal static class WebMessageManager | |
{ | |
private readonly static JsonSerializerOptions s_jsonSerializerOptions = new JsonSerializerOptions | |
{ | |
AllowTrailingCommas = true, | |
IncludeFields = true, | |
}; | |
private static IDictionary<string, IWebMessageHandler> _webMessagesHandler = new Dictionary<string, IWebMessageHandler>(); | |
public static void RegistrateHandler(IWebMessageHandler messageHandler) | |
{ | |
_webMessagesHandler.Add(messageHandler.Action, messageHandler); | |
} | |
public static void WebMessageHandle(string jsonData) | |
{ | |
WebMessage? message = JsonSerializer.Deserialize<WebMessage>(jsonData, s_jsonSerializerOptions); | |
if (message != null && _webMessagesHandler.TryGetValue(message.Action, out IWebMessageHandler? webMessagesHandler)) | |
{ | |
webMessagesHandler?.OnAction(message.ID, message.Value); | |
} | |
} | |
} | |
internal sealed class WebMessage | |
{ | |
[JsonPropertyName("action")] | |
public string Action = null!; | |
[JsonPropertyName("id")] | |
public string? ID = null; | |
[JsonPropertyName("value")] | |
public string? Value = null; | |
} | |
internal interface IWebMessageHandler | |
{ | |
public CoreWebView2 WebView { get; internal init; } | |
public string Action { get; internal init; } | |
void OnAction(string? id, string? data); | |
} | |
internal abstract class WebMessageHandlerBase : IWebMessageHandler | |
{ | |
private readonly static JsonSerializerOptions s_jsonSerializerOptions = new JsonSerializerOptions | |
{ | |
AllowTrailingCommas = true, | |
IncludeFields = true, | |
}; | |
public string Action { get; init; } | |
public CoreWebView2 WebView { get; init; } | |
internal WebMessageHandlerBase(CoreWebView2 webView, string actionName) | |
{ | |
WebView = webView; | |
Action = actionName; | |
} | |
public abstract void OnAction(string? id, string? data); | |
public void Respose<T>(string? id, T data) | |
where T : class | |
{ | |
WebMessage webMessage = new WebMessage | |
{ | |
Action = Action, | |
ID = id, | |
Value = JsonSerializer.Serialize(data, s_jsonSerializerOptions) | |
}; | |
string message = JsonSerializer.Serialize(webMessage, s_jsonSerializerOptions); | |
WebView.PostWebMessageAsJson(message); | |
} | |
} | |
/// JS | |
const webMessageManager = (()=>{ | |
const actions = {}; | |
window.chrome.webview.addEventListener('message', e => { | |
actions[e.data.id](JSON.parse(e.data.value)); | |
delete actions[e.data.id]; | |
}); | |
function sendMessage(action, id, data) { | |
var msgObject = { | |
action: action, | |
id: id, | |
value: JSON.stringify(data) | |
}; | |
var json = JSON.stringify(msgObject); | |
window.chrome.webview.postMessage(json); | |
} | |
return { | |
sendMessage: (action, data) => { | |
sendMessage(action, null, data); | |
}, | |
postMessage: (action, data) => { | |
var id = crypto.randomUUID(); | |
console.log(id); | |
sendMessage(action, id, data); | |
return new Promise((resolve) => { | |
actions[id] = resolve; | |
}); | |
} | |
}; | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment