Newbie: Access variables from main.js in BrowserWindow preload


In my BrowserWindow preload, I can assign some global variables and access them after loadURL, but I’d like to assign the global variable based on variables in my main.js. How can I do that?

Thank you and Happy New Year :slightly_smiling:

Edit: What I mean is…

In my preload.js, I have the following:

process.once(‘loaded’, function() {
global.myVariable = 1234;

Then, when I loadURL, I can open DevTools and see myVariable is 1234 at the console. How can I set myVariable to something from main.js instead of hard coded?


From your main.js you can use variableNameOfYourBrowserWindowObject.webContents.executeJavaScript

Like so: mainWindow.webContents.executeJavaScript("window.electronFlag=true;console.log('hello from ELECTRON');");

You also have access to ES6 template strings, so if you’re adding the number dynamically, you could do something like this:

var myVariable = 1234;
  `global={myVariable: ${myVariable}};`


Thank you caffiend!

This gives me flexibility to get done what I wanted to do, but out of curiosity, how could I get a variable from main.js into preload.js that will execute before the page loads (webPreferences: preload)?

Thanks again and happy new year!