我如何从电子中的主进程访问BrowserWindow JavaScript全局

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

本文关键字:进程 访问 BrowserWindow 全局 JavaScript      更新时间:2023-09-26

我想要一个在主进程中定义的菜单,以调用Atom或Electron应用程序中当前浏览器窗口内的JavaScript代码。

从浏览器窗口获取主进程全局变量

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

什么是等效的主进程(AKA获取当前窗口全局变量)?这就是我在伪代码

中要做的
// 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')

这里是你对API中webContents过程的评论的参考,在"注:"在遥控器。

然而,如果你只是想触发一个函数,你也可以使用webcontent .send()和ipc(主进程)进程来触发相应的代码运行。像这样…

// JavaScript inside the 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
});

对于电子版本0.35.0及以上,ipc API更改如下:

// In main process.
const ipcMain = require('electron').ipcMain;
// In renderer process (web page).
const ipcRenderer = require('electron').ipcRenderer;

电子版本11.x。你可以这样做

// 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
});