问题描述
我想要一个菜单,在主进程中定义,在原子/电子应用程序的当前浏览器窗口中调用JS代码。
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')
推荐答案
是对您对webContents流程的评论的引用在api中,在注意:下遥控器。
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
});
更新:
电子版0.35 .0及以上,ipc api更改为以下内容:
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;
这篇关于如何从电子主进程中访问BrowserWindow Javascript全局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!