Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access BrowserWindow Javascript global from main process in electron?

I want a menu, defined in the main process to call JS code inside the current browser window in an atom/electron application.

Getting main process globals form the browser window is

const remote = require('remote') const foo    = remote.getGlobal('foo') 

What is the equivalent for the main process (aka get current window globals). This is what I want to do in pseudo-code

// JS inside main process const BrowserWindow = require('browser-window') //... // Inside the menu callback let window    = BrowserWindow.getFocusedWindow() let commander = window.global('commander') /// <---- PSEUDO-CODE !!! commander.handleCommand('File.Save') 
like image 408
Anna B Avatar asked Jun 06 '15 10:06

Anna B


People also ask

What is Electron BrowserWindow?

The BrowserWindow class exposes various ways to modify the look and behavior of your app's windows.

What is a preload script Electron?

A preload script contains code that runs before your web page is loaded into the browser window. It has access to both DOM APIs and Node. js environment, and is often used to expose privileged APIs to the renderer via the contextBridge API.

What is main process in Electron JS?

The main process' primary purpose is to create and manage application windows with the BrowserWindow module. Each instance of the BrowserWindow class creates an application window that loads a web page in a separate renderer process.


1 Answers

Here is a reference to your comment about the webContents process in the api, in the "Note:" under remotes.

However, if you just want to trigger a function, you could also use the webContents.send() and ipc(main process) processes to trigger the appropriate code to run. Something like this...

// JS inside main process const window = require('electron').BrowserWindow;  ipc.on('menuItem-selected', function(){     let focusedWindow    = window.getFocusedWindow();     focusedWindow.webContents.send('file-save'); });  // Inside the menu callback require('ipc').on('file-save', function() {   // File save function call here }); 

Update:

For Electron version 0.35.0 and above, the ipc api changed to the following:

// In main process. const ipcMain = require('electron').ipcMain;  // In renderer process (web page). const ipcRenderer = require('electron').ipcRenderer; 
like image 109
Josh Avatar answered Sep 19 '22 15:09

Josh