Reputation: 6137
I want a menu, defined in the main process to call JavaScript code inside the current browser window in an Atom or Electron application.
Getting main process globals from the browser window is
const remote = require('remote')
const foo = remote.getGlobal('foo')
What is the equivalent for the main process (AKA get the current window globals)? This is what I want to do in pseudocode
// JavaScript inside the main process
const BrowserWindow = require('browser-window')
//...
// Inside the menu callback
let window = BrowserWindow.getFocusedWindow()
let commander = window.global('commander') /// <---- Pseudocode!!!
commander.handleCommand('File.Save')
Upvotes: 40
Views: 53626
Reputation: 3390
For electron version 11.x.x you can do this
// In renderer process
const { ipcRenderer } = window.require("electron");
ipcRenderer.on("your-event-here", () => {
//hand your event here
});
//In the main process
import { ipcMain } from "electron";
ipcMain.handle("handle-event-here", async (event, data) => {
// write custom code here
});
Upvotes: 0
Reputation: 3345
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...
// JavaScript inside the 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
});
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;
Upvotes: 48