Search code examples
javascriptglobal-variableselectronglobalelectron-packager

Call window function from electron


In one .js file I have

window.functionName = function(){

}

Now I want to call the function in the main electron file. How can I do that?

Here is what I tried to do in the main electron file:

const electron = require('electron');
const BrowserWindow = electron.BrowserWindow; 
var focusedWindow = BrowserWindow.getFocusedWindow();
focusedWindow.functionName();

It does not work. Why?


Solution

  • getFocusedWindow returns BrowserWindow object. BrowserWindow is electron's window object, not actual browser's global context - so none of window. global object is being exposed in BrowserWindow automatically. What you may need is get webContents via focusedWindow.webContents then ask renderer process to execute your javascript via executeJavaScript method. Main process and rendere process (browserWindow) are separate process, so you can't direcly invoke function right away but have to ask it.