iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 11
0
Modern Web

ElectronJS系列 第 11

[ Day 11 ] - 動物聊天室(四) - preload 在 vue 中的特殊設定

[ Day 11 ] - 動物聊天室(四) - preload 在 vue 中的特殊設定

在 [ Day 09 ] 時了解要用到 IPC 需要在 preload.js 中取得 ipcRenderer 才能跟 Main Process 的 ipcMain 傳遞訊息
而在 vue 框架上要如何設定 preload.js 呢 ?

本魯以為在 vue 上的做法 , 跟一般 html 的設定方式相同 ,

因此 , 本魯按照 [ Day 8 ] 的做法建立一個含有 electron 功能的 vue 專案 ,

然後在 background.js 中的 new BrowserWindow 區塊追加參數 preload

win = new BrowserWindow({
        ...
        webPreferences: {
            // Use pluginOptions.nodeIntegration, leave this alone
            // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
            nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
+            preload: path.join(__dirname, 'preload.js'),
        }
    })

結果 , 在 devtool 中出現 preload.js not found 的錯誤訊息

本魯只好到 vue-cli-plugin-electron-builder 官方文件 查查在 vue 中到底要如何設定 preload ?

原來 , 需要在根目錄新建檔案 vue.config.js 讓 preload.js 在編譯後 , 產生一個 preload.js 到 dist_electron 資料夾中

module.exports = {
  pluginOptions: {
    electronBuilder: {
      preload: 'src/preload.js',
      // Or, for multiple preload files:
      // preload:{ preload: 'src/preload.js', otherPreload: 'src/preload2.js'}
    }
  }
}

在 preload.js 中設定 window.ipcRenderer = ipcRendereripcRenderer 掛到 chromium 的 window 底下

// in preload.js
const {ipcRenderer} = require('electron');
window.ipcRenderer = ipcRenderer;

在 vue 的 component 中我們就可以使用 window.ipcRenderer.onwindow.ipcRenderer.send 與 ipcMain 傳遞訊息了 !

備註

如果 devtool 沒有顯示 , 可以使用快捷鍵 ctrl+shift+I 把 devtool 叫出來 !

參考資料

今年小弟第一次參加 `鐵人賽` , 如文章有誤 , 請各位前輩提出指正 , 感謝  <(_ _)>

上一篇
[ Day 10 ] - 動物聊天室(三) - firestore 介紹
下一篇
[ Day 12 ] - 動物聊天室(五) - 動物聊天室畫面
系列文
ElectronJS38
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言