电子浏览器窗口

时间:2017-12-06 12:00:12

标签: electron

我的电子申请中有2 BrowserWindow个实例,mainWindowsecondaryWindowmainWindow中有一个按钮,点击后会打开secondaryWindow

现在我的问题是,在mainWindow关闭之前,我不希望能够点击secondaryWindow中的任何内容。

我最接近的是使用mainWindow.hide(),但这只是完全隐藏了窗口,我想在mainWindow处于活动状态时看到secondaryWindow,但应该禁用/ {不活动的。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

有两种方法可以打开子窗口:

<强> 1。来自主要流程:

您可以从主进程打开子窗口。例如,这对菜单中的自定义窗口很有用。

在这里,您可以使用构造函数使其成为parent的子项。如果属性modal为true,则在子窗口关闭之前将无法访问父窗口。

function createChild(parent, html) {
  //creates modal window
  child = new BrowserWindow({
    width: 786,
    height: 847,
    parent: parent,
    modal: true,
    show: false
  });
  child.loadURL(html);
  child.webContents.openDevTools();
  child.once("ready-to-show", () => {
    child.show();
  });
}

<强> 2。来自渲染器过程

现在,我们并不总是希望通过IPC将事件发送到主进程只是为了打开一个子窗口,对吗?

我们不需要。我们可以在窗口中使用open函数。

例如:

const button = document.querySelector('button')
button.addEventListener('click', e => {
     self.open(`file://${__dirname}/child.html`)
})

要使此窗口成为父窗体和模态窗口的子窗口,可以在父窗口中注册eventlistener:

parent.webContents.on(
    "new-window",
    (event, url, frameName, disposition, options, additionalFeatures) => {
      Object.assign(options, {
        parent: parent,
        modal: true
      });
    }
  );

这样,当在父窗口上调用window.open()时,它将打开一个模态子窗口。

示例

main.js

const { app, BrowserWindow } = require("electron");

let win;
function createWindow() {
  win = new BrowserWindow({ width: 1000, height: 800 });
  win.loadURL(`file://${__dirname}/index.html`);
  win.webContents.openDevTools();
  win.on("closed", () => {
    win = null;
  });

  win.webContents.on(
    "new-window",
    (event, url, frameName, disposition, options, additionalFeatures) => {
      Object.assign(options, {
        parent: win,
        modal: true
      });
    }
  );
}

app.on("ready", createWindow);

的index.html

<!DOCTYPE html>
<html>

<body>
    <p>I am the parent, you can't touch me until you closed my child!</p>
    <button>Open child!</button>
    <script>
        const button = document.querySelector('button')
        button.addEventListener('click', e => {
            self.open(`file://${__dirname}/child.html`)
        })
    </script>
</body>

</html>

child.html

<!DOCTYPE html>
<html>

<body>
    I'm the child!
</body>

</html>