2

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?

cutMeDown
  • 55
  • 6

1 Answers1

2

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.

OJ Kwon
  • 4,385
  • 1
  • 20
  • 24
  • How could I execute the function `functionName` in my case? Provide an example, please. – cutMeDown Dec 11 '17 at 18:49
  • For anyone else with this issue, the way to do this is `mainWindow.webContents.executeJavaScript("functionName();");`. This function can also be used to call other JS operations in the browser window. – SuperJumpBros Aug 04 '22 at 20:59