1

In order to maintain security thanks to contextIsolation: false I typically make ipcRenderer available to the renderer process by creating a global variable in preload.js like this:

const electron = require('electron');

process.once('loaded', () => {
  global.ipcRenderer = electron.ipcRenderer;
});

Then, ipcRenderer can be directly used in my (primary) renderer process:

<script>
...
ipcRenderer.send(...)
...
</script>

However, when I am opening a second window (i.e., I am creating a second renderer process), ipcRenderer is not defined. Why can't the second renderer process access my global variable? How can I resolve this issue? Thank you very much for your help!

bassman21
  • 320
  • 2
  • 11
  • Please [edit] your question and include the code you use to open *both* `BrowserWindow`s, the first one as well as the second. Thanks! – Alexander Leithner May 02 '21 at 08:47
  • Thank you very much for your comment! I think, I have found the answer myself (by trying a lot of different approaches). I will put my answer below and would highly appreciate if you could tell me if my answer is correct (or makes sense, at least). – bassman21 May 02 '21 at 09:22

1 Answers1

0

I have tried many things and I think that I have found a solution. However, I have no idea whether this is the "best practice" way to do it. Any opinion from the community would be highly appreciated.

The second renderer process can access the global variable ipcRenderer if it also uses the same preload.js. I thought that using preload.js again would be somehow redundant or even wrong, but it solves the issue. Here is the code that worked:

function openModal() {
  let modalWin = new BrowserWindow({
    parent: win,
    modal: true,
    width: 400,
    height: 300,
    show: false,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: false
    }
  })

  modalWin.loadFile('modal.html');
  modalWin.once('ready-to-show', () => {
    modalWin.show()
  })
}
bassman21
  • 320
  • 2
  • 11
  • This is not ideal because it exposes the whole ipcRenderer and disables ContextIsolation. You should be safe if you don't load any remote content at all, however it is still better to use a safer approach, just in case. This answer is more secure since it only exposes needed functions and channels: https://stackoverflow.com/a/59675116/13752696 – Autumn May 04 '21 at 08:29