【问题标题】:How to access the mainWindow from another script in Electron?如何从 Electron 中的另一个脚本访问 mainWindow?
【发布时间】:2018-10-24 02:29:48
【问题描述】:

我的电子应用在 main.js 中定义了BrowserWindow mainWindow。它加载一个 html,并最终在 html 内部运行一个脚本运行函数 dialog.showMessageBox(),它会显示一个简单的警告:

dialog.showMessageBox({
    type: 'warning',
    message: "You have been warned.",
    buttons: ["OK"]
});

我希望此对话框成为 mainWindow b/c 的子级,使其成为模式,从而禁用 mainWindow 直到它关闭。要实现这一点,您通常只需在类型声明之前添加mainWindow,。不幸的是,它不知道变量 mainWindow,因为 dialog.showMessageBox() 是在不同的脚本 (site.js) 中创建的。

如何创建一个对话框,它是 mainWindow 的子级,而不在 main.js 中创建它? ipc 能帮上忙吗?

【问题讨论】:

    标签: javascript node.js modal-dialog electron


    【解决方案1】:

    您可以使用 Electron 的 remote 模块从该窗口中包含(加载)的脚本中获取当前的 BrowserWindow

    const remote = require ("electron").remote;
    
    dialog.showMessageBox (remote.getCurrentWindow (), {
      type: "warning",
      message: "You have been warned.",
      buttons: ["OK"]
    });
    

    【讨论】:

      【解决方案2】:

      接受的答案仍然正确,但相当陈旧,与此同时,Electron 团队决定慢慢弃用 remote 模块(更多信息 herehere):


      但是,我能够通过使用BrowserWindow.getFocusedWindow() 来修复它,这仅做了一个微小的假设,即触发 MsgBox 的窗口是当前关注的窗口(我的猜测是在 99% 的情况下这是正确的) .这是更新后的代码:

      const { dialog, BrowserWindow } = require ("electron");
      
      dialog.showMessageBox (BrowserWindow.getFocusedWindow(), {
        type: "warning",
        message: "You have been warned.",
        buttons: ["OK"]
      });
      

      【讨论】:

        【解决方案3】:

        为了安全地在 electron 中获取 mainWindow,我将其 ID 存储在一个 env 变量中,并在需要时调用 BrowserWindow.fromId(ID)

        BrowserWindow.getFocusedWindow() 在某些情况下不起作用,例如,如果您将 URL 从子窗口加载到主窗口。
        我也遇到了一些奇怪的效果,BrowserWindow.getAllWindows() 解决方案。

        // store the ID at init time when you create your main window
        process.env.MAIN_WINDOW_ID = mainWindow.id;
        
        // every time you want the main window, call this function.
        // don't forget to convert the env variable to type number otherwise this will throw an error.
        const getMainWindow = () => {
          const ID = process.env.MAIN_WINDOW_ID * 1;
          return BrowserWindow.fromId(ID)
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多