-
Notifications
You must be signed in to change notification settings - Fork 3
/
ElectronPreload.ts
58 lines (50 loc) · 2.26 KB
/
ElectronPreload.ts
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
52
53
54
55
56
57
58
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module Renderer
*/
import type { IpcRendererEvent } from "electron";
import { contextBridge, ipcRenderer } from "electron";
/** These methods are stored on `window.itwinjs` */
export interface ITwinElectronApi {
addListener: (channel: string, listener: ElectronListener) => void;
removeListener: (channel: string, listener: ElectronListener) => void;
invoke: (channel: string, ...data: any[]) => Promise<any>;
once: (channel: string, listener: (event: any, ...args: any[]) => void) => void;
send: (channel: string, ...data: any[]) => void; // only valid for render -> main
}
/**
* This file is loaded as an Electron preload script
* (see https://www.electronjs.org/docs/api/browser-window#class-browserwindow) from ElectronMain.ts
*/
function checkPrefix(channel: string) {
if (!channel.startsWith("itwin."))
throw new Error(`illegal channel name '${channel}'`);
}
type ElectronListener = (event: IpcRendererEvent, ...args: any[]) => void;
/** the implementation of the private api between the frontend (renderer) and backend (main) iTwin.js processes in Electron. */
const frontendApi: ITwinElectronApi = {
send(channel: string, ...data: any[]) {
checkPrefix(channel);
ipcRenderer.send(channel, ...data);
},
addListener(channel: string, listener: ElectronListener) {
checkPrefix(channel);
ipcRenderer.addListener(channel, listener);
},
removeListener(channel: string, listener: ElectronListener) {
ipcRenderer.removeListener(channel, listener);
},
once(channel: string, listener: ElectronListener) {
checkPrefix(channel);
ipcRenderer.once(channel, listener);
},
async invoke(channel: string, ...data: any[]): Promise<any> {
checkPrefix(channel);
return ipcRenderer.invoke(channel, ...data);
},
};
// this adds the frontendApi object under the name `window.itwinjs` in the frontend Electron process.
contextBridge.exposeInMainWorld("itwinjs", frontendApi);