Electron 上下文隔离和 node 集成

Context isolation and Node integration

Scenario	contextIsolation	nodeIntegration	Remarks
A	false	false	Preload is not needed. Node.js is available in the Main but not in the Renderer.
B	false	true	Preload is not needed. Node.js is available in the Main and Renderer.
C	true	false	Preload is needed. Node.js is available in the Main and Preload but not in the Renderer. Default. Recommended.
D	true	true	Preload is needed. Node.js is available in the Main, Preload, and Renderer.

see: https://stackoverflow.com/questions/57807459/how-to-use-preload-js-properly-in-electron

Main

//electron
import electron from 'electron';
const app = electron.app;
import path from 'path';
// @ts-ignore
import index from '!!file-loader?name=[name].[ext]!./index.html';

function createWindow() {
    // Create the browser window.
    var mainWindow = new electron.BrowserWindow({
        width: 1000,
        height: 600,
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: path.join(__dirname, './preload.js'), // dist/preload.js
        },
    })
    mainWindow.loadFile(index);
    console.log('main pid: ', process.pid);
}

app.on('ready', createWindow);

Preload

globalThis.addEventListener('DOMContentLoaded', () => {
  console.log('preload pid: ', process.pid);
});

ipc 通信

Main:

    electron.ipcMain.handle('version', () => {
        return process.version;
    });

Preload:

import { contextBridge, ipcRenderer } from 'electron';

contextBridge.exposeInMainWorld('api', {
  send(channel, data) {
    return ipcRenderer.invoke(channel, data);
  }
});

Renderer:

<button onclick="api.send('version').then(version => alert(version))">TEST</button>

see

https://www.electronjs.org/zh/docs/latest/tutorial/quick-start

posted @ 2023-05-23 16:10  develon  阅读(242)  评论(0编辑  收藏  举报