如何从电子的主进程访问 BrowserWindow Javascript global?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30681639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access BrowserWindow Javascript global from main process in electron?
提问by gaspard
I want a menu, defined in the main process to call JS code inside the current browser window in an atom/electron application.
我想要一个在主进程中定义的菜单,用于在原子/电子应用程序中调用当前浏览器窗口内的 JS 代码。
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')
回答by Josh
Hereis a reference to your comment about the webContents process in the api, in the "Note:" under remotes.
这是您对 api 中 webContents 进程的评论的参考,在遥控器下的“注意:”中。
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...
但是,如果您只想触发一个函数,您也可以使用webContents.send()和ipc(main process)进程来触发相应的代码运行。像这样的东西...
// 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:
对于 Electron 0.35.0 及以上版本,ipc api 更改为以下内容:
// In main process.
const ipcMain = require('electron').ipcMain;
// In renderer process (web page).
const ipcRenderer = require('electron').ipcRenderer;

