【问题标题】:Using IPC layer and contextBridge to send data to renderer in Electron使用 IPC 层和 contextBridge 将数据发送到 Electron 中的渲染器
【发布时间】:2021-06-22 22:41:46
【问题描述】:

我把不相关的部分去掉了:

main.js

let window = null;
 app.on('ready', () => {
    window = new BrowserWindow({
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            enableRemoteModule: false,
            preload: path.join(__dirname, "preload.js")
        }
    });

    window.loadFile('index.html')
        .then(() => {})
        .catch(err => console.log(err));
});

我在 main.js 中有一个超时调用

window.webContents.send('store-data', "MESSAGE");

preload.js

const {contextBridge,ipcRenderer} = require('electron');

contextBridge.exposeInMainWorld('electron', {
    storeData: (channel, data) => {
        ipcRenderer.on(channel, (event, data) => {
            return data;
        });
    }
});

index.html

window.electron.storeData('store-data', (data) =>{
    console.log(data);
});

这是因为我在 index.html 端获得了一个对象,但没有数据。

【问题讨论】:

    标签: electron ipc


    【解决方案1】:

    我从从事 Electron 工作的人那里获得了帮助。注意:需要仔细监控和过滤 IPC 层之间的通信,以防止出现安全问题。

    main.js

    let window = null;
    
    app.on('ready', () => {
        window = new BrowserWindow({
            webPreferences: {
                nodeIntegration: false,
                contextIsolation: true,
                enableRemoteModule: false,
                allowRunningInsecureContent: false,
                experimentalFeatures: false,
                preload: path.join(__dirname, "preload.js")
            }
        });
    
        window.loadFile('index.html')
            .then(() => {})
            .catch(err => console.log(err));
    });
    
    ipcMain.on('save', (event,text) => {
        setTimeout(()=>{
            event.sender.send('store-data', text);
        }, 1000) 
    });
    

    请不要超时和回调仅用于演示目的。这更像是一个概念证明。

    preload.js

    const {contextBridge,ipcRenderer} = require('electron');
    
    contextBridge.exposeInMainWorld('electron', {
        saveToElectron: (text) => ipcRenderer.send('save', text),
        storeData: (channel, func) => {
            ipcRenderer.on(channel, func);
        }
    });
    

    index.html 的 JS

        window.electron.storeData('store-data', (event,  data) =>{
            console.log("From Server: "+  data);
        });
    

    这主要是从 main 向渲染进程发送一条消息...并附加一个事件侦听器来侦听该消息(在此示例中,它导致保存文件)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-29
      • 2021-05-13
      • 2022-01-11
      • 2021-04-02
      • 1970-01-01
      • 2018-09-17
      • 2018-10-10
      相关资源
      最近更新 更多