How to access BrowserWindow Javascript global from main process in electron?(如何从电子的主进程访问 BrowserWindow Javascript 全局?)
问题描述
我想要一个在主进程中定义的菜单,用于在原子/电子应用程序的当前浏览器窗口中调用 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 全局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从电子的主进程访问 BrowserWindow Javascript 全局


基础教程推荐
- 响应更改 div 大小保持纵横比 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 动态更新多个选择框 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01