Electron: How to securely inject global variable into BrowserWindow / BrowserView?

After doing some digging, I found a few pull requests for Electron that detail the issue you are having. The first describes a reproducible example very similar to the problem you are describing.

Expected Behavior

https://electronjs.org/docs/tutorial/security#3-enable-context-isolation-for-remote-content A preload script should be able to attach anything to the window or document with contextIsolation: true.

Actual behavior

Anything attached to the window in the preload.js just disappears in the renderer.

It seems the final comment explains that the expected behavior no longer works

It was actually possible until recently, a PR with Isolated Worlds has changed the behavior.

The second has a user suggest what they have found to be their solution:

After many days of research and fiddling with the IPC, I've concluded that the best way is to go the protocol route.

I looked at the docs for BrowserWindow and BrowserView as well as an example that shows the behavior that you desire, but these PRs suggest this is no longer possible (along this route).

Possible Solution

Looking into the documentation, the webContents object you get from view.webContents has the function executeJavaScript, so you could try the following to set the global variable.

...
view.setAutoResize({ width: true, height: true });
view.webContents.loadURL('http://localhost:3000');
view.webContents.executeJavaScript("global.baz = 'qux';");
...