Electron中两个渲染器进程之间的通信

Communicating between two renderer processes in Electron

本文关键字:进程 之间 通信 两个 Electron      更新时间:2023-09-26

我正在编写一个Eletron程序。在程序中,有一个由主进程(main.js)创建的索引窗口。在这个窗口中有一个文件(图像)列表。当我点击该列表中的一个文件时,我想启动第二个窗口来显示该文件。第二个窗口是由索引窗口的渲染器进程(index.js)启动的。如何在索引窗口的呈现器进程和第二个窗的呈现器过程之间进行通信?

代码:

从main.js:中的主进程创建索引窗口

let win;
function createWindow(){
  // Create the browser window.
  win = new BrowserWindow({width: 1024, height: 768, minWidth: 800, minHeight: 600, show: false, icon: 'files/images/icon.png'});
  win.loadURL(`file://${__dirname}/files/html/index.html`);
  win.once('ready-to-show', () => {
    win.show()
  })
  // Emitted when the window is closed.
  win.on('closed', () => {
    win = null;
  });
}
app.on('ready', createWindow);

在index.html index.js(渲染器进程)中启动:

<script src="../javascript/index.js"></script>

在index.js中调用function create_sprite_window(),它创建一个子窗口:

const fs = require('fs');
const path = require('path');
const {BrowserWindow} = require('electron').remote
let child_windows = [];

function create_child_window(URL, width, height){
  let rem_win = require('electron').remote.getCurrentWindow();
  let new_win = new BrowserWindow({width: width, height: height, minWidth: 400, minHeight: 300, show: false, parent: rem_win, minimizable: true, maximizable: true, skipTaskbar: true});
  child_windows[child_windows.length] = new_win;
  console.log(child_windows);
  new_win.loadURL(URL);
  new_win.once('ready-to-show', () => {
    new_win.show()
  })
  return new_win;
}
function create_sprite_window(){
  new_win = create_child_window(`file://${__dirname}/../html/sprite_manager.html`, 800, 400);
}

子窗口存储在数组CCD_ 2中。

然后,是否可以将图像的路径发送到第二窗口,或者,从索引窗口编辑第二窗口的<img>标签(将第二窗口中<img>标签的源设置为具有getElementById.src = path;的图像)?。

我自己找到了答案。为了在第二个渲染器窗口中显示正确的图像,我在包含图像路径的URL中添加了一个GET参数。