All is well in the development, the console prints contextBridge normally
enter image description here
After packing into a desktop application using electron-builder, the console prints contextBridge undefined
enter image description here
I try to console electron object in preload.js, it contains contextBridge in development but there is no contextBridge in package application, did I make a mistake when packing?
main.js
const {app, BrowserWindow, Menu, MenuItem, ipcMain} = require('electron');
const path = require("path");
const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');
const adapter = new FileSync('./FSconfig.json', {
serialize: (data) => JSON.stringify(data),
deserialize: (data) => JSON.parse(data)
})
const db = low(adapter);
let win;
let windowConfig = {
icon: './img/icon.png',
width: 1000,
height: 800,
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
preload: path.join(__dirname, 'preload.js')
}
};
function createWindow() {
win = new BrowserWindow(windowConfig);
win.loadURL(`${__dirname}/index.html`);
win.on('close', () => {
win = null;
});
win.on('resize', () => {
win.reload();
})
}
ipcMain.on('modifyJson', (event, args) => {
for (let item in args) {
if (args.hasOwnProperty(item)) {
db.set(item, args[item]).write()
}
}
})
app.on('ready', createWindow);
app.on('window-all-closed', () => {
app.quit();
});
app.on('activate', () => {
if (win == null) {
createWindow();
}
});
preload.js
const {contextBridge, ipcRenderer} = require('electron');
cconsole.log(contextBridge, 'contextBridge');
console.log(ipcRenderer, 'ipcRenderer');
contextBridge.exposeInMainWorld('modify', {
write: (modifyValue) => ipcRenderer.send('modifyJson', modifyValue)
})
package.json
{
"name": "appelectron",
"version": "1.0.0",
"description": "a Application",
"main": "main.js",
"scripts": {
"start": "electron .",
"pack": "electron-builder --win --x64",
"dist": "electron-builder",
"postinstall": "install-app-deps"
},
"author": "",
"license": "ISC",
"devDependencies": {
"electron": "^16.0.7",
"electron-builder": "^22.14.5"
},
"build": {
"appId": "修改配置",
"copyright": "Copyright © 2021-forever zjing",
"artifactName": "修改配置-${version}-${arch}.${ext}",
"win": {
"requestedExecutionLevel": "highestAvailable",
"target": [
{
"target": "nsis",
"arch": [
"x64"
]
}
]
},
"electronVersion": "1.0.0",
"nsis": {
"oneClick": false,
"allowToChangeInstallationDirectory": true,
"createDesktopShortcut": true,
"artifactName": "修改配置-${version}-${arch}.${ext}"
},
"extraResources": [
{
"from": "./static/img/",
"to": "app-server",
"filter": [
"**/*"
]
},
{
"from": "./FSconfig.json",
"to": "../FSconfig.json"
}
]
},
"dependencies": {
"lowdb": "^1.0.0"
}
}