在 Electron 中创建多个应用程序实例

Create multiple instance of app in Electron

我到处搜索,但找不到如何创建电子应用程序的多个实例。我正在尝试创建一个 便签 应用程序,其中有一个加号 window,它应该创建一个新的便签,而该便签又将具有相同的加号按钮。

我已经尝试过了,但是第一次点击便签上的加号按钮时出现了一个大问题,创建了一个新实例,但是第二次点击加号按钮 2 创建了新实例,第三次点击加号按钮 4已创建新实例

Inside main.js file

let mainWindow

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 190, height: 190,frame:false,transparent:true})

  mainWindow.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))
  mainWindow.on('closed', function () {
    mainWindow = null
  })
  //when plus button is clicked it is firing a message 'create-new-instance' through ipcRenderer
  ipcMain.on('create-new-instance',()=>{
    console.log('create new window');
    createWindow();
  })
}

//this is called when for the first time the app is launched
app.on('ready', createWindow)

Inside renderer.js file where plus button is located

document.getElementById('plusButton').addEventListener("click", ()=>{
    var {ipcRenderer} = require('electron')
    ipcRenderer.send('create-new-instance')
})

问题是当我第一次点击加号按钮时 'create-new-instance' 被触发并且因为只有一个笔记实例(在您第一次启动应用程序时创建)创建了一个新笔记使其成为 2 个笔记实例都能够收听 'create-new-instance' 事件,当我第二次单击加号按钮时,两个音符都会收听此事件并创建 1 个音符,每个音符总共有 4 个音符。

请帮助我或建议我使用其他替代方法:)

这里的主要问题是您要为 createWindow() 中的 create-new-instance 事件添加一个侦听器,因此每次 createWindow() 运行时都会添加另一个事件侦听器,并且当 create-new-instance 被发出,每个听众都会创建一个新的 window。为避免这种情况,您需要将事件订阅移到 createWindow() 之外,这样无论 createWindow() 被调用多少次,事件都只有一个侦听器。