如何从电子的主进程访问 BrowserWindow Javascript 全局

How to access BrowserWindow Javascript global from main process in electron?(如何从电子的主进程访问 BrowserWindow Javascript 全局?)
本文介绍了如何从电子的主进程访问 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 全局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)