electron-with-create-react-app icon indicating copy to clipboard operation
electron-with-create-react-app copied to clipboard

The trick no longer works

Open thany opened this issue 3 years ago • 2 comments

That trick to getting ipcRenderer exposed, no longer works. You'll need a ridiculously stupid and verbose workaround to get to it. I blame Electron for not playing nice with tools in the past, and for not providing this solution to issues raised about the plethora of errors from workarounds - no longer functioning, mind you - floating around all over SO and Github and whatnot.

  1. Add a preload config:
const mainWindow = new BrowserWindow({
  width: 800,
  height: 600,
  webPreferences: {
    preload: path.join(__dirname, 'electron-preload.js')
  }
});
  1. Expose stuff in the preload file (in ./src/electron-preload.js in this case):
// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
const { contextBridge, ipcRenderer } = require("electron");

// As an example, here we use the exposeInMainWorld API to expose the browsers
// and node versions to the main window.
// They'll be accessible at "window.ipcRenderer".
process.once("loaded", () => {
  contextBridge.exposeInMainWorld("ipcRenderer", ipcRenderer);
});
  1. If using typescript, place this somwhere in a sensible file as well:
import { IpcRenderer } from 'electron';

declare global {
  interface Window {
    ipcRenderer: IpcRenderer
  }
}
  1. Now you can use window.ipcRenderer anywhere in the app.

thany avatar Oct 19 '21 23:10 thany

Thanks for the details on the workaround. At some point I need to revisit this template and update it for a more current version of electron.

csepulv avatar Oct 19 '21 23:10 csepulv

I figured if I'm spending 2 hours gettings this to work, I might as well share it 😀

thany avatar Oct 20 '21 00:10 thany