問題描述
我想要一個在主進程中定義的菜單,用于在原子/電子應用程序的當前瀏覽器窗口中調用 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 全局?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!