筆者最近收到做桌面端的需求,為了一套代碼滿足mac和Windows,遂選擇了flutter,在調(diào)研flutter桌面端的時候,發(fā)現(xiàn)flutter對于Windows的內(nèi)嵌webview不太友好,需要在包里集成WebView2,同時webview上如果在添加組件的話,也有滑動上的問題,項目中會有大量的webview上的需求,遂放棄了flutter,選用electron肚逸。
electron 集成還是超級簡單的,我選用的是在vue2項目下添加electron支持,剩下的就是前端開發(fā)了,但是在打開新的子窗口時,遇到了electron 最近的一個更新,在vue界面中,不能直接通過 const { ipcRenderer } = window.require('electron'); 獲取ipcRenderer,需要添加一個preload.js,來進行中轉,百度了一下,發(fā)現(xiàn)相關資料較少,官網(wǎng)說的也不太直白,這里做下科普吧,主要是給新手electron 開發(fā)看的,嘿嘿
這是一個項目目錄.先手動添加preload.js,里面內(nèi)容為
const { contextBridge, ipcRenderer } = require('electron');
const validChannels = ['show-read-win',];
contextBridge.exposeInMainWorld(
'ipc', {
send: (channel, data) => {
if (validChannels.includes(channel)) {
ipcRenderer.send(channel, data);
}
},
on: (channel, func) => {
if (validChannels.includes(channel)) {
// Strip event as it includes `sender` and is a security risk
ipcRenderer.on(channel, (event, ...args) => func(...args));
}
},
},
);
修改vue.config.js為
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
pluginOptions: {
electronBuilder: {
preload: 'src/preload.js' //make sure you have this line added
}
}
})
然后再background.js中引入
const path = require('path');
const win = new BrowserWindow({
minWidth: 1024,
minHeight: 768,
width: 1024,
height: 768,
center: true,
transparent: false,
frame: true, // 隱藏窗口邊框
backgroundColor: '#00000000', // 透明背景色
skipTaskbar: false,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION
}
})
這里面有個問題是path,報錯我忘了截圖.需要下載
npm install path-browserify #這個庫
然后添加webpack.config.js文件,里面內(nèi)容
const path = require('path');
module.exports = {
resolve: {
fallback: {
"fs": false,
"path": require.resolve("path-browserify")
}
},
};
這樣就可以直接使用啦,在主窗口
window.ipc.send("show-read-win"); //就可以直接發(fā)送通知
在background.js進行接收
ipcMain.on('show-read-win', () => {
if (childWindow === null) {
createChildWindow();
} else {
childWindow.show();
}
});
這樣就全部完成啦,有什么問題可以留言探討~
Electron Mac 打包報 Error: Exit code: ENOENT. spawn /usr/bin/python 如何解決
which python
找到自己的2.7python目錄
/Library/Frameworks/Python.framework/Versions/2.7/bin/python
然后找到目錄下的/node_modules/dmg-builder/out/dmg.js
將
"/usr/bin/python" 修改成 /Library/Frameworks/Python.framework/Versions/2.7/bin/python 就可以了
參考資料
https://medium.com/swlh/how-to-safely-set-up-an-electron-app-with-vue-and-webpack-556fb491b83
生命不息,代碼不止!碼農(nóng)一枚,請多點贊