electron 端的 ’jsbridge‘ 实现
发布于 4 年前 作者 bosscheng 4266 次浏览 来自 分享

背景

想通过一套代码既能跑在浏览器端,又能跑在electron 端,这个时候就需要electron 在使用 BrowserWindow 的时候,参数上面需要添加webPreferences参数

代码

// main.js
const mainViwndo = new BrowserWindow({
    webPreferences: {
        webSecurity: false,
        nodeIntegration: true,
        preload: path.join(__dirname, 'preload.js'),
    },
})

这样的话,在 preload.js 里面就可以

// preload.js
window._ipcRenderer = require('electron').ipcRenderer;
window._remote = require('electron').remote;
window._platform = process.platform;

通过这样的形式,就可以支持代码既能跑在electron端又能跑在浏览器端。

然后业务端使用


// electron-client.js
const _rpc = window._ipcRenderer;

export function minWindow() {
    _rpc && _rpc.send('minWindow');
}

export function maxWindow() {
    _rpc && _rpc.send('maxWindow');
}

export function closeWindow() {
    _rpc && _rpc.send('closeWindow');
}

export function unMaxWindow() {
    _rpc &&  _rpc.send('unMaxWindow');

}

然后接触 is-electron 库,在业务代码中进行

const isInElectron = isElectron();

if(isInElectron){
    // electron 端
}
else{
    // 浏览器端
}

回到顶部