问题描述
我想要一个在主进程中定义的菜单,用于在原子/电子应用程序的当前浏览器窗口中调用 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')
推荐答案
这里 是对您对 api 中 webContents 进程的评论的引用,位于遥控器下的注意:"中.
Here is a reference to your comment about the webContents process in the api, in the "Note:" under remotes.
但是,如果你只是想触发一个函数,你也可以使用 webContents.send() 和 ipc(main process) 进程触发相应的代码运行.像这样的...
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
});
更新:
对于 Electron 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 全局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!