【问题标题】:Electron pass creator window id to new BrowserWindowElectron 将创建者窗口 ID 传递给新的 BrowserWindow
【发布时间】:2018-09-06 14:54:40
【问题描述】:

我正在制作一个在后台在网站上运行自定义脚本的电子应用程序。此代码正在主窗口创建的第二个窗口中执行。然后第二个窗口创建另一个隐藏窗口,将在其中加载网站并运行自定义脚本。我需要能够将第二个窗口的窗口 id 传递给隐藏窗口,这样当自定义脚本完成运行时,它可以专门将 ipc 消息发送回第二个窗口。

我在github 上发现了一个问题,有人在 2016 年回答说您似乎可以分配自定义值来获胜,然后在新创建的窗口中阅读它们,但我没有成功实施。

        // In second window
        const currentWindow = require('electron').remote.getCurrentWindow();
        // Create hidden window
        win = new BrowserWindow({ show: false });
        win.creatorId = currentWindow.id; // CUSTOM: Set creator window ID
        win.webContents.openDevTools();
        win.webContents.on('dom-ready', () => {
            // Load dependencies every time a new url is loaded
            win.webContents.executeJavaScript(`
                const currentWindow = require('electron').remote.getCurrentWindow();
                alert(currentWindow.creatorId); // This is undefined :(
                const { BrowserWindow } = require('electron').remote;
                const ipc = require('electron').ipcRenderer;
                window.$ = window.jQuery = require('jquery');
            `);
        });

        ...

        worker.win.loadURL(`random.webpage`);
        // Run custom script on a website and send the result back to the creator window
        win.webContents.executeJavaScript(`
            $(document).ready(function () { 
BrowserWindow.fromId(currentWindow.creatorId).webContents.send('coolMessage', {});
            });
    `);

当我尝试读取 win.creatorId 时,它是未定义的。如何从隐藏窗口中识别第二个窗口,以便向它发送消息?

【问题讨论】:

    标签: javascript electron


    【解决方案1】:

    在您的win.webContents.executeJavaScript 中,您可以像这样在执行 javascript 函数中设置变量:

    win.webContents.executeJavaScript("var creatorId = " + currentWindow.webContents.id + ";");
    

    这意味着您可以删除:win.creatorId = currentWindow.id;。并更改:

    BrowserWindow.fromId(currentWindow.creatorId).webContents.send('coolMessage', {});
    

    收件人:

    BrowserWindow.fromId(creatorId).webContents.send('coolMessage', {});
    

    webContents.id Docs

    【讨论】:

    • 当我尝试打印 id 时仍然不确定。我用占位符字符串尝试了相同的代码,即win.creatorId = "2",但在尝试从隐藏窗口打印时仍然未定义。
    • 将它作为字符串中的变量传递,多么简单而美好的想法。谢谢!
    猜你喜欢
    • 2019-07-31
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 2013-02-05
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多