简体   繁体   English

如何从 Electron 中的主进程访问 BrowserWindow JavaScript 全局?

[英]How can I access the BrowserWindow JavaScript global from the main process in Electron?

I want a menu, defined in the main process to call JavaScript code inside the current browser window in an Atom or Electron application.我想要一个在主进程中定义的菜单,用于在AtomElectron应用程序中的当前浏览器 window 中调用 JavaScript 代码。

Getting main process globals from the browser window is从浏览器 window 获取主进程全局变量是

const remote = require('remote')
const foo    = remote.getGlobal('foo')

What is the equivalent for the main process (AKA get the current window globals)?主进程的等价物是什么(又名获取当前的 window 全局变量)? This is what I want to do in pseudocode这就是我想用伪代码做的

// JavaScript inside the main process
const BrowserWindow = require('browser-window')
//...
// Inside the menu callback
let window    = BrowserWindow.getFocusedWindow()
let commander = window.global('commander') /// <---- Pseudocode!!!
commander.handleCommand('File.Save')

Here is 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. 但是,如果您只想触发一个函数,您还可以使用webContents.send()ipc(主进程)进程来触发运行的相应代码。 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
});

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;

For electron version 11.xx you can do this对于 electron 版本 11.xx,您可以执行此操作

// In renderer process

const { ipcRenderer } = window.require("electron");

ipcRenderer.on("your-event-here", () => {

    //hand your event here 
    
});


//In the main process

import { ipcMain } from "electron";

ipcMain.handle("handle-event-here", async (event, data) => {

  // write custom code here

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM