Reputation: 176
Im bulding an app with Electron using Vite and React.
Everything work fine except when i try to make call to the electron process (main/index.js) from the renderer in the browser (dev mode npm run dev
). it works fine from the electron window, but in browser window.electron
is undefined.
I'm not sure where the preload script is running in the browser and if at all.
ive set contextIsolation
to false
. When I build, it all works. the problem is only in dev server in browser env.
Any help?
--main/index.js--
const mainWindow = new BrowserWindow({
width: 2000,
height: 2000,
show: false,
autoHideMenuBar: true,
webPreferences: {
contextIsolation: false,
preload: join(__dirname, '../preload/index.js'),
sandbox: false,
devTools: true,
},
});
---preload---
import { contextBridge } from 'electron';
import { electronAPI } from '@electron-toolkit/preload';
// Custom APIs for renderer
const api = {};
// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
try {
contextBridge.exposeInMainWorld('electron', electronAPI);
contextBridge.exposeInMainWorld('api', api);
} catch (error) {
console.error(error);
}
} else {
// @ts-ignore (define in dts)
window.electron = electronAPI;
// @ts-ignore (define in dts)
window.api = api;
}
--react app (renderer)--
useEffect(() => {
console.log({ electron: window.electron });
window.electron?.ipcRenderer.on('transcode-video-complete', (_, { binary }) => {
setLoading(false);
downloadFile(binary, 'output.mp4', 'video/mp4');
});
}, [window.electron]);
Upvotes: 0
Views: 111