Skip to content

Commit 0a0713d

Browse files
committed
fix(stage-tamagotchi): better type checks with exposeWithCustomAPI
1 parent 04e8b21 commit 0a0713d

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

apps/stage-tamagotchi/src/preload/shared.ts

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { contextIsolated, platform } from 'node:process'
55
import { electronAPI } from '@electron-toolkit/preload'
66
import { contextBridge, ipcRenderer } from 'electron'
77

8-
export function expose<CustomApi = unknown>(customApi: CustomApi = undefined as CustomApi) {
8+
export function expose() {
99
// TODO: once we refactored eventa to support window-namespaced contexts,
1010
// we can remove the setMaxListeners call below since eventa will be able to dispatch and
1111
// manage events within eventa's context system.
@@ -18,7 +18,6 @@ export function expose<CustomApi = unknown>(customApi: CustomApi = undefined as
1818
try {
1919
contextBridge.exposeInMainWorld('electron', electronAPI)
2020
contextBridge.exposeInMainWorld('platform', platform)
21-
contextBridge.exposeInMainWorld('api', customApi)
2221
}
2322
catch (error) {
2423
console.error(error)
@@ -27,6 +26,24 @@ export function expose<CustomApi = unknown>(customApi: CustomApi = undefined as
2726
else {
2827
window.electron = electronAPI
2928
window.platform = platform
30-
;(window as ElectronWindow<CustomApi>).api = customApi
29+
}
30+
}
31+
32+
export function exposeWithCustomAPI<CustomAPI>(customAPI: CustomAPI) {
33+
expose()
34+
35+
// Use `contextBridge` APIs to expose Electron APIs to
36+
// renderer only if context isolation is enabled, otherwise
37+
// just add to the DOM global.
38+
if (contextIsolated) {
39+
try {
40+
contextBridge.exposeInMainWorld('api', customAPI)
41+
}
42+
catch (error) {
43+
console.error(error)
44+
}
45+
}
46+
else {
47+
(window as ElectronWindow<CustomAPI>).api = customAPI
3148
}
3249
}

0 commit comments

Comments
 (0)