javascript - 如何从 Electron 中的另一个脚本访问 mainWindow?

标签 javascript node.js modal-dialog electron

我的 Electron 应用程序在 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有什么帮助吗?

最佳答案

当前 Electron 版本 (>= 14.0.0)

从 Electron 14.0.0 开始,下面提到的 remote 模块已经是 deprecated and subsequently removed .为了仍然从渲染器进程打开这些对话框,我建议通过 IPC 向主进程发送消息:

// renderer process
const { ipcRenderer  } = require ("electron");

ipcRenderer.send ("show-message");

以及主进程中的监听部分:

// main process
const { dialog, ipcMain, BrowserWindow } = require ("electron");

ipcMain.on ("show-message", (event, args) => {
    dialog.showMessageBox (BrowserWindow.fromWebContents (event.sender), {
        type: "warning",
        message: "You have been warned.",
        buttons: ["OK"]
    });
});

这将为已发送 IPC 消息的 BrowserWindow 实例打开消息框作为模态对话框,因此将作为 remote 的直接替代品代码。


Electron <14.0.0

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

const remote = require ("electron").remote;

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

关于javascript - 如何从 Electron 中的另一个脚本访问 mainWindow?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50330153/

相关文章:

javascript - 使用 jQuery .load() 加载的页面不响应其他 JavaScript

javascript - 如何保护 React 应用程序中的 API key ?

javascript - 遍历 socket.io v1 中的套接字? "...has no method ' 客户的”

CSS 位置 : sticky behaves like fixed (within w3. css 模态)

modal-dialog - ReactJs:使用 Portal 包装语义 UI 模态 "pattern"

javascript - Jquery-从 HTML 表创建 JavaScript 对象

javascript - 如何替换列表中特定索引处的元素

javascript - Angular 4 - 如何在 HTML 中显示 3rdpartylicenses

javascript - 如何强制 Google Apps 脚本等待用户在加载下一个 htmlOutput 之前选择一个 HtmlOutput 上的按钮?

node.js - Amazon Cognito 确认密码失败并显示 (TypeError : Converting circular structure to JSON)