-
Notifications
You must be signed in to change notification settings - Fork 10
/
webview2.js
51 lines (45 loc) · 1.42 KB
/
webview2.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// the keys should match enum keys in c#
export const WV2EVENTS = {
SelectionChanged: "SelectionChanged",
getEventName(key) {
return this[key]?.toLowerCase();
},
};
const eventCaptureElement = document.createElement("a");
// this is called by WebView2 from C#
window.dispatchWebViewEvent = function dispatchWebViewEvent({ action, payload }) {
console.log(`dispatch requested ${action}`);
const e = WV2EVENTS.getEventName(action);
if (e !== undefined) {
console.log(`dispatching event ${e}`);
console.log(`event payload : ${payload}`);
eventCaptureElement.dispatchEvent(new CustomEvent(e, { detail: payload }));
}
};
export function subscribeToWebView2Event(eventName, handler) {
const e = WV2EVENTS.getEventName(eventName);
// console.log(`subscribing: ${e}`);
if (e === undefined) {
return;
}
// console.log(`subscribed: ${e}`);
eventCaptureElement.addEventListener(e, handler);
}
export function unsubscribeToWebView2Event(eventName, handler) {
const e = WV2EVENTS.getEventName(eventName);
// console.log(`unsubscribing: ${e}`);
if (e === undefined) {
return;
}
// console.log(`unsubscribed: ${e}`);
eventCaptureElement.removeEventListener(e, handler);
}
export function postWebView2Message({ action, payload }) {
if (!action) {
return;
}
window.chrome?.webview?.postMessage({ action, payload });
}
export function isInWebViewContext() {
return !!window.chrome?.webview;
}