Electron通過預加載腳本從渲染器訪問Node.js

問題:如何實現輸出Electron的版本號和它的依賴項到你的web頁面上?

答案:在主進程通過Node的全局?process?對象訪問這個信息是微不足道的。 然而,你不能直接在主進程中編輯DOM,因為它無法訪問渲染器?文檔?上下文。 它們存在于完全不同的進程!這是將?預加載?腳本連接到渲染器時派上用場的地方。預加載腳本在渲染器進程加載之前加載,并有權訪問兩個 渲染器全局 (例如?window?和?document) 和 Node.js 環境。

1.創建預加載腳本?

在項目的src/preload/目錄下創建一個名為?preload.js?的新腳本如下:?

const { contextBridge, ipcRenderer } = require('electron')contextBridge.exposeInMainWorld('electronAPI', {onUpdateCounter: (callback) => ipcRenderer.on('update-counter', (_event, value) => callback(value)),setTitle: (title) => ipcRenderer.send('set-title', title)
})

2.在主進程中引入

在主進程的background.js文件中,引入預加載腳本如下:

 // 指定預加載腳本webPreferences: {// 啟用上下文隔離contextIsolation: true,// 禁用 Node.js 集成,因為我們將通過預加載腳本來提供所需的功能nodeIntegration: false,// 禁用 remote 模塊,出于安全考慮enableRemoteModule: false,// 設置預加載腳本preload: path.join(__dirname, "preload.js"),},

這里使用了兩個Node.js概念:

  • __dirname?字符串指向當前正在執行腳本的路徑 (在本例中,它指向你的項目的根文件夾)。
  • path.join?API 將多個路徑聯結在一起,創建一個跨平臺的路徑字符串。

我們使用一個相對當前正在執行JavaScript文件的路徑,這樣您的相對路徑將在開發模式和打包模式中都將有效。

background.js文件?

'use strict'import { app, protocol, BrowserWindow, ipcMain, Menu } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
// import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
const isDevelopment = process.env.NODE_ENV !== 'production'
const path = require('path')
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([{ scheme: 'app', privileges: { secure: true, standard: true } }
])async function createWindow() {// Create the browser window.const win = new BrowserWindow({width: 800,height: 600,// 指定預加載腳本webPreferences: {// 啟用上下文隔離contextIsolation: true,// 禁用 Node.js 集成,因為我們將通過預加載腳本來提供所需的功能nodeIntegration: false,// 禁用 remote 模塊,出于安全考慮enableRemoteModule: false,// 設置預加載腳本preload: path.join(__dirname, "preload.js"),},// 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,//   contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION// }})///ipcMain.on('set-title', (event, title) => {const webContents = event.senderconsole.log(`接收到渲染進程消息:`, title);event.reply('update-counter', title)})console.log(`path.join(__dirname, "preload.js")`, path.join(__dirname, "preload.js"));///if (process.env.WEBPACK_DEV_SERVER_URL) {// Load the url of the dev server if in development modeawait win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)if (!process.env.IS_TEST) win.webContents.openDevTools()} else {createProtocol('app')// Load the index.html when not in developmentwin.loadURL('app://./index.html')}
}// Quit when all windows are closed.
app.on('window-all-closed', () => {// On macOS it is common for applications and their menu bar// to stay active until the user quits explicitly with Cmd + Qif (process.platform !== 'darwin') {app.quit()}
})app.on('activate', () => {// On macOS it's common to re-create a window in the app when the// dock icon is clicked and there are no other windows open.if (BrowserWindow.getAllWindows().length === 0) createWindow()
})// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {// if (isDevelopment && !process.env.IS_TEST) {//   // Install Vue Devtools//   try {//     //await installExtension(VUEJS_DEVTOOLS)//   } catch (e) {//     console.error('Vue Devtools failed to install:', e.toString())//   }// }createWindow()
})// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {if (process.platform === 'win32') {process.on('message', (data) => {if (data === 'graceful-exit') {app.quit()}})} else {process.on('SIGTERM', () => {app.quit()})}
}

?3.在主進程和渲染進程中使用預加載腳本

主進程中使用:

 ipcMain.on('set-title', (event, title) => {const webContents = event.senderconsole.log(`接收到渲染進程消息:`, title);event.reply('update-counter', title)})

?主進程完整腳本文件

'use strict'import { app, protocol, BrowserWindow, ipcMain, Menu } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
// import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
const isDevelopment = process.env.NODE_ENV !== 'production'
const path = require('path')
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([{ scheme: 'app', privileges: { secure: true, standard: true } }
])async function createWindow() {// Create the browser window.const win = new BrowserWindow({width: 800,height: 600,// 指定預加載腳本webPreferences: {// 啟用上下文隔離contextIsolation: true,// 禁用 Node.js 集成,因為我們將通過預加載腳本來提供所需的功能nodeIntegration: false,// 禁用 remote 模塊,出于安全考慮enableRemoteModule: false,// 設置預加載腳本preload: path.join(__dirname, "preload.js"),},// 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,//   contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION// }})///ipcMain.on('set-title', (event, title) => {const webContents = event.senderconsole.log(`接收到渲染進程消息:`, title);event.reply('update-counter', title)})console.log(`path.join(__dirname, "preload.js")`, path.join(__dirname, "preload.js"));///if (process.env.WEBPACK_DEV_SERVER_URL) {// Load the url of the dev server if in development modeawait win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)if (!process.env.IS_TEST) win.webContents.openDevTools()} else {createProtocol('app')// Load the index.html when not in developmentwin.loadURL('app://./index.html')}
}// Quit when all windows are closed.
app.on('window-all-closed', () => {// On macOS it is common for applications and their menu bar// to stay active until the user quits explicitly with Cmd + Qif (process.platform !== 'darwin') {app.quit()}
})app.on('activate', () => {// On macOS it's common to re-create a window in the app when the// dock icon is clicked and there are no other windows open.if (BrowserWindow.getAllWindows().length === 0) createWindow()
})// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {// if (isDevelopment && !process.env.IS_TEST) {//   // Install Vue Devtools//   try {//     //await installExtension(VUEJS_DEVTOOLS)//   } catch (e) {//     console.error('Vue Devtools failed to install:', e.toString())//   }// }createWindow()
})// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {if (process.platform === 'win32') {process.on('message', (data) => {if (data === 'graceful-exit') {app.quit()}})} else {process.on('SIGTERM', () => {app.quit()})}
}

渲染進程中使用:

<template><div><div>接收主進程的消息{{ ShowData }}</div><button @click="sendToMain">Send Message to Main</button></div>
</template><script>
export default {data() {return {ShowData: 0,};},methods: {sendToMain() {const title = Math.round(Math.random() * 100);window.electronAPI.setTitle(title);},},mounted() {// 監聽主進程的回復window.electronAPI.onUpdateCounter((value) => {console.log(`接收主進程的消息:`, value);this.ShowData = value;});},//   beforeDestroy() {//     // 在組件銷毀前,移除事件監聽器//  window.ipcRenderer.removeAllListeners("reply-from-main");//   },
};
</script>

注意:開發環境時主進程使用的是軟件編譯后dist_electron目錄下的preload.js?預加載文件

?到這里在開發環境就能使用預加載腳本實現主進程和渲染進程通信了

4.在vue.config.js中進行electron打包配置

如果想在electron打包后的軟件中仍然可以正常使用預加載腳本文件的話,必須在vue.config.js文件中進行相應的打包配置。

  pluginOptions: {electronBuilder: {removeElectronJunk: false,preload: './src/preload/preload.js',builderOptions: {"appId": "voloday_test","productName": "voloday_test",//項目名,也是生成的安裝文件名,即.exe"copyright": "Copyright ? 2024",//版權信息"win": {//win相關配置// "icon": "./src/assets/icon.ico",//圖標,當前圖標在根目錄下"target": [{"target": "nsis",//利用nsis制作安裝程序"arch": ["x64",//64位]}]},"nsis": {"oneClick": false, // 是否一鍵安裝"allowElevation": true, // 允許請求提升。 如果為false,則用戶必須使用提升的權限重新啟動安裝程序。"allowToChangeInstallationDirectory": true, // 允許修改安裝目錄// "installerIcon": "./src/assets/icon.ico",// 安裝圖標// "uninstallerIcon": "./src/assets/icon.ico",//卸載圖標// "installerHeaderIcon": "./src/assets/icon.ico", // 安裝時頭部圖標"createDesktopShortcut": true, // 創建桌面圖標"createStartMenuShortcut": true,// 創建開始菜單圖標"shortcutName": "voloday_test", // 圖標名稱},}},},

vue.config.js文件?

const { defineConfig } = require('@vue/cli-service')
const path = require("path");
console.log(`path.join(__dirname,'preload.js')`, path.join(__dirname,'preload.js'));
module.exports = defineConfig({transpileDependencies: true,publicPath: './',pluginOptions: {electronBuilder: {removeElectronJunk: false,preload: './src/preload/preload.js',builderOptions: {"appId": "voloday_test","productName": "voloday_test",//項目名,也是生成的安裝文件名,即.exe"copyright": "Copyright ? 2024",//版權信息"win": {//win相關配置// "icon": "./src/assets/icon.ico",//圖標,當前圖標在根目錄下"target": [{"target": "nsis",//利用nsis制作安裝程序"arch": ["x64",//64位]}]},"nsis": {"oneClick": false, // 是否一鍵安裝"allowElevation": true, // 允許請求提升。 如果為false,則用戶必須使用提升的權限重新啟動安裝程序。"allowToChangeInstallationDirectory": true, // 允許修改安裝目錄// "installerIcon": "./src/assets/icon.ico",// 安裝圖標// "uninstallerIcon": "./src/assets/icon.ico",//卸載圖標// "installerHeaderIcon": "./src/assets/icon.ico", // 安裝時頭部圖標"createDesktopShortcut": true, // 創建桌面圖標"createStartMenuShortcut": true,// 創建開始菜單圖標"shortcutName": "voloday_test", // 圖標名稱},}},},})

源碼:GitHub - 1t1824d/elctron29.0.0_node18.19.0_vuecli5.0.8_vue2?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/717748.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/717748.shtml
英文地址,請注明出處:http://en.pswp.cn/news/717748.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【軟考】數據庫的三級模式

目錄 一、概念1.1 說明1.2 數據庫系統體系結構圖 二、外模式三、概念模式四、內模式 一、概念 1.1 說明 1.數據的存儲結構各不相同&#xff0c;但體系結構基本上具有相同的特征&#xff0c;采用三級模式和兩級鏡像 2.數據庫系統設計員可以在視圖層、邏輯層和物理層對數據進行抽…

matplotlib散點圖

matplotlib散點圖 假設通過爬蟲你獲取到了北京2016年3, 10月份每天白天的最高氣溫(分別位于列表a, b), 那么此時如何尋找出氣溫和隨時間(天)變化的某種規律? from matplotlib import pyplot as pltx_3 range(1, 32) x_10 range(51, 82)y_3 [11,17,16,11,12,11,12,6,6,7,8…

試手一下CameraX(APP)

書接上回。 首先還是看谷歌的官方文檔&#xff1a; https://developer.android.com/media/camera/camerax?hlzh-cn https://developer.android.com/codelabs/camerax-getting-started?hlzh-cn#1 注&#xff1a;這里大部分內容也來自谷歌文檔。 官方文檔用的是Kotlin&…

常用的字符字符串的讀取方法(C / C++)

一、字符 1、讀取單個字符&#xff1a;直接讀取 //輸入a //讀取 char x; scanf("%c",&x); 2、讀取帶空格的字符 h h h 按格式書寫格式化字符串即可 char a,b,c; scanf("%c %c %c",&a,&b,&c); 3、 處理字符間的換行符 假設要讀取以…

Day14:信息打點-主機架構蜜罐識別WAF識別端口掃描協議識別服務安全

目錄 Web服務器&應用服務器差異性 WAF防火墻&安全防護&識別技術 蜜罐平臺&安全防護&識別技術 思維導圖 章節知識點 Web&#xff1a;語言/CMS/中間件/數據庫/系統/WAF等 系統&#xff1a;操作系統/端口服務/網絡環境/防火墻等 應用&#xff1a;APP對象/…

小程序圖形:echarts-weixin 入門使用

去官網下載整個項目&#xff1a; https://github.com/ecomfe/echarts-for-weixin 拷貝ec-canvs文件夾到小程序里面 index.js里面的寫法 import * as echarts from "../../components/ec-canvas/echarts" const app getApp(); function initChart(canvas, width, h…

Vscode 使用SSH遠程連接樹莓派的教程(解決卡在Downloading with wget)

配置Vscode Remote SSH 安裝OpenSSH 打開Windows開始頁面&#xff0c;直接進行搜索PowerShell&#xff0c;打開第一個Windows PowerShell&#xff0c;點擊以管理員身份運行 輸入指令 Get-WindowsCapability -Online | ? Name -like OpenSSH* 我是已經安裝好了&#xff0c;…

學會玩游戲,智能究竟從何而來?

最近在讀梅拉妮米歇爾《AI 3.0》第三部分第九章&#xff0c;談到學會玩游戲&#xff0c;智能究竟從何而來&#xff1f; 作者: [美] 梅拉妮米歇爾 出版社: 四川科學技術出版社湛廬 原作名: Artificial Intelligence: A Guide for Thinking Humans 譯者: 王飛躍 / 李玉珂 / 王曉…

基于springboot實現計算機類考研交流平臺系統項目【項目源碼+論文說明】

基于springboot實現計算機類考研交流平臺系統演示 摘要 高校的大學生考研是繼高校的高等教育更上一層的表現形式&#xff0c;教育的發展是我們社會的根本&#xff0c;那么信息技術的發展又是改變我們生活的重要因素&#xff0c;生活當中各種各樣的場景都存在著信息技術的發展。…

程序員超強大腦——更好地解決編程問題(二)

概念機器 概念機器是計算機的抽象表征&#xff0c;可以借此分析計算機執行的操作。 程序員不僅經常借助概念機器推理計算機的運行方式&#xff0c;而且往往用它來分析代碼。例如&#xff0c;雖然并不存在能夠出存儲數值的實體&#xff0c;但程序員還是會將變量描述為“保存”…

Debezium發布歷史163

原文地址&#xff1a; https://debezium.io/blog/2023/09/23/flink-spark-online-learning/ 歡迎關注留言&#xff0c;我是收集整理小能手&#xff0c;工具翻譯&#xff0c;僅供參考&#xff0c;筆芯筆芯. Online machine learning with the data streams from the database …

SpringBlade CVE-2022-27360 export-user SQL 注入漏洞分析

漏洞描述 SpringBlade是一個基于Spring Cloud和Spring Boot的開發框架&#xff0c;旨在簡化和加速微服務架構的開發過程。它提供了一系列開箱即用的功能和組件&#xff0c;幫助開發人員快速構建高效可靠的微服務應用。該產品/api/blade-user/export-user接口存在SQL注入。 漏…

Java - List集合與Array數組的相互轉換

一、List 轉 Array 使用集合轉數組的方法&#xff0c;必須使用集合的 toArray(T[] array)&#xff0c;傳入的是類型完全一樣的數組&#xff0c;大小就是 list.size() public static void main(String[] args) throws Exception {List<String> list new ArrayList<S…

無處不在的智慧:探索嵌入式系統的奇妙

無處不在的智慧&#xff1a;探索嵌入式系統的奇妙 嵌入式系統作為當今科技領域中無處不在的一種技術&#xff0c;其奇妙之處正在逐步被揭示和探索。從智能家居到智能穿戴設備&#xff0c;從工業自動化到醫療健康&#xff0c;嵌入式系統已經深入到我們生活和工作的方方面面&…

分布式ID生成策略-雪花算法Snowflake

分布式ID生成策略-雪花算法Snowflake 一、其他分布式ID策略1.UUID2.數據庫自增與優化2.1 優化1 - 共用id自增表2.2 優化2 - 分段獲取id 3.Reids的incr和incrby 二、雪花算法Snowflake1.雪花算法的定義2.基礎雪花算法源碼解讀3.并發1000測試4.如何設置機房和機器id4.雪花算法時鐘…

【misc | CTF】BUUCTF 二維碼

天命&#xff1a;這題使用到腳本暴力破解壓縮包文件里面的密碼&#xff0c;還是比較有意思的 一開始是一個二維碼&#xff0c;掃碼進去有一個假flag 扔進圖片隱寫工具&#xff0c;啥也沒有&#xff0c;都是同一個二維碼 使用工具&#xff1a;foremost&#xff0c;直接分離圖片&…

【詳識JAVA語言】抽象類和接口

抽象類 抽象類概念 在面向對象的概念中&#xff0c;所有的對象都是通過類來描繪的&#xff0c;但是反過來&#xff0c;并不是所有的類都是用來描繪對象的&#xff0c;如果 一個類中沒有包含足夠的信息來描繪一個具體的對象&#xff0c;這樣的類就是抽象類。 比如&#xff1a;…

水印相機小程序源碼

水印相機前端源碼&#xff0c;本程序無需后端&#xff0c;前端直接導入即可&#xff0c;沒有添加流量主功能&#xff0c;大家開通后自行添加 源碼搜索&#xff1a;源碼軟件庫 注意小程序后臺的隱私權限設置&#xff0c;前端需要授權才可使用 真實時間地址拍照記錄&#xff0c…

Endnote x9 最快方法批量導入.enw格式文件

按照網上看到的一個方法直接選中所有enw批量拖拽到 All references 附件不行啊&#xff0c; 以為只能寫bat腳本方式了 經過一番嘗試&#xff0c;驚人的發現拖到下面這個符號的地方就行了&#xff01;&#xff01;&#xff01; 如果不成功的話&#xff0c;可能&#xff1a; 我…

使用typescript實現引入vue3生命周期函數的基礎知識整理

在Vue 3中&#xff0c;生命周期函數被更改為組合式API&#xff0c;并且不再使用官方命名的生命周期鉤子函數。不過&#xff0c;我們仍然可以模擬類似的功能&#xff0c;使用onBeforeMount、onMounted、onBeforeUpdate、onUpdated、onBeforeUnmount、onUnmounted等組合式API。 …