【问题标题】:How can I open a new modal browser windows from a render process in electron如何从电子的渲染过程中打开新的模态浏览器窗口
【发布时间】:2021-03-19 06:32:14
【问题描述】:

在渲染过程中使用new BrowserWindow 语句时,会引发以下异常:TypeError: BrowserWindow is not a constructor

如何从渲染进程创建新的模态 BrowserWindow?

【问题讨论】:

    标签: electron


    【解决方案1】:

    您不能在渲染器进程中使用BrowserWindow。仅在主进程中:

    https://www.electronjs.org/docs/api/browser-window#browserwindow

    两个进程必须通过通道进行通信:

    // main process
    const {app, BrowserWindow, ipcMain} = require('electron')
    
    app.whenReady().then(function () {
      const mainWindow = new BrowserWindow({ webPreferences: { nodeIntegration: true } });
      mainWindow.loadFile('index.html');
    });
    
    ipcMain.on('go!', (ev, url) => {
    //         ^^^^^
    //         A channel called "go!"
      new BrowserWindow().loadURL(url);
    });
    
    // renderer process
    const {ipcRenderer} = require('electron');
    
    document.querySelector('button').addEventListener('click', function () {
      ipcRenderer.send('go!', 'https://www.discogs.com/artist/7760-Japanese-Telecom');
    });
    
    <html>
      <body>
        <button>detroit techno</button>
        <script>require('./renderer.js')</script>
      </body>
    </html>
    

    当你点击“detroit techno”按钮时(你应该这样做!):

    1. 渲染器进程发送带有 url 的消息
    2. 主进程拾取消息并在新窗口中打开url

    【讨论】:

    • 感谢您的反馈。只是为了确保我理解:如果渲染进程需要打开一个简单的对话框(例如输入一些文本),这必须通过主进程执行吗?
    • @doberkofler 如果你想使用BrowserWindow API,那么可以。
    • 请注意,您不需要设置nodeIntegration=true来启用进程之间的IPC通信。见stackoverflow.com/q/69605882/1244884
    猜你喜欢
    • 2011-02-18
    • 2020-05-11
    • 2020-11-05
    • 1970-01-01
    • 2017-12-09
    • 1970-01-01
    • 2016-12-20
    • 2018-07-28
    • 2019-02-05
    相关资源
    最近更新 更多