【问题标题】:Electron check if a window is already open and close before creatingElectron 在创建之前检查窗口是否已经打开和关闭
【发布时间】:2020-09-05 14:33:28
【问题描述】:

是否可以在电子中检测窗口是否已经创建并在创建另一个窗口之前关闭?

这是我的示例代码

// video window listener
ipcMain.on("load-video-window", (event, data) => {
  // create the window

  //window.close() if window exist;

  let videoPlayer = new BrowserWindow({
    show: true,
    width: 840,
    height: 622,
    webPreferences: {
      nodeIntegration: true,
      plugins: true,
    },
  });

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    videoPlayer.loadURL(
      process.env.WEBPACK_DEV_SERVER_URL + "video_player.html"
    );
    if (!process.env.IS_TEST) videoPlayer.webContents.openDevTools();
  } else {
    videoPlayer.loadURL(`app://./video_player`);
  }

  videoPlayer.on("closed", () => {
    videoPlayer = null;
  });

  // here we can send the data to the new window
  videoPlayer.webContents.on("did-finish-load", () => {
    videoPlayer.webContents.send("data", data);
  });
});

【问题讨论】:

    标签: windows electron destroy


    【解决方案1】:

    我认为这应该可行

    let playerWindow;
    ipcMain.on("load-video-window", (event, data) => {
    
      if (playerWindow) {
        playerWindow.close();
      }
    
      playerWindow = new BrowserWindow();
    
    });
    

    【讨论】:

    • 感谢您的反馈,关闭窗口就像这样,但在新打开时出现错误Uncaught Exception: TypeError: Cannot read property 'webContents' of null
    【解决方案2】:

    扩展@Lord Midi 代码,我们可以检查一个窗口是否没有被破坏并且仍然是可聚焦的。您可以使用以下代码做到这一点:

    let playerWindow;
    const isPlayerWindowOpened = () => !playerWindow?.isDestroyed() && playerWindow?.isFocusable();
    
    ipcMain.on("load-video-window", (event, data) => {
    
      if (isPlayerWindowOpened()) {
        playerWindow.close();
      }
    
      playerWindow = new BrowserWindow();
    
    })
    

    【讨论】:

    • 为确保您解决了核心问题,您能否更新您的答案以包括如何应用此代码来关闭已打开的窗口?我意识到这是您在这里所写内容的一个微不足道的扩展,它解决了核心挑战。但由于这是问题的一部分,因此演示实现将很有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    相关资源
    最近更新 更多