I'm trying to understand how to effectively load the proload.js file in electron:
Version "electron": "^9.1.2", Version "electron-builder": "^22.8.0",
In background.js I put
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
//preload: path.join(app.getAppPath(), "preload.js"),
preload: path.join(__dirname, "./preload.js"),
},
preload.js and background.js are in the same folder: src folder.
this is my preload.js :
const {
contextBridge,
ipcRenderer
} = require("electron");
const path = require("path");
contextBridge.exposeInMainWorld(
"api", {
send: (channel, data) => {
// whitelist channels
let validChannels = ["toMain"];
if (validChannels.includes(channel)) {
ipcRenderer.send(channel, data);
}
},
receive: (channel, func) => {
let validChannels = ["fromMain"];
if (validChannels.includes(channel)) {
// Deliberately strip event as it includes `sender`
ipcRenderer.on(channel, (event, ...args) => func(...args));
}
}
}
);
webpack.config.js :
import 'script-loader!./script.js';
import webpack from 'webpack';
const path = require('path');
module.exports = {
target: ['electron-renderer', 'electron-main', 'electron-preload'],
pluginOptions: {
electronBuilder: {
chainWebpackMainProcess: config => {
config.resolve.alias.set('jsbi', path.join(__dirname, 'node_modules/jsbi/dist/jsbi-
cjs.js'));
}
},
},
};
module.exports = {
entry: './src/background.js',
target: 'node',
output: {
path: path.join(__dirname, 'build'),
filename: 'backend.js'
}
}
module.exports = config => {
config.target = "electron-renderer";
return config;
};
I get these error messages:
vue info
Environment Info:
System:
OS: Linux 5.4 Ubuntu 18.04.4 LTS (Bionic Beaver)
CPU: (8) x64 Intel(R) Core(TM) i7-4790K CPU @ 4.00GHz
Binaries:
Node: 14.5.0 - ~/.nvm/versions/node/v14.5.0/bin/node
Yarn: 1.22.4 - /usr/bin/yarn
npm: 6.14.5 - ~/.nvm/versions/node/v14.5.0/bin/npm
npmGlobalPackages:
@vue/cli: 4.4.6
vue.config.js :
module.exports = {
pluginOptions: {
electronBuilder: {
// Prevent bundling of certain imported packages and instead retrieve these external
dependencies at runtime.
// In order to connect to websocket.
externals: ['ggc'],
builderOptions: {
productName: 'GGC',
win: {
icon: './public/app.ico'
},
mac: {
icon: './public/icons/Icon.icns',
target: [
'pkg',
'dmg',
'zip',
],
},
linux: {
icon: './public/app.png'
}
}
}
}
}
// https://nklayman.github.io/vue-cli-plugin-electron-builder/guide/configuration.html#webpack-
configuration
module.exports = {
configureWebpack: {
// Configuration applied to all builds
},
pluginOptions: {
electronBuilder: {
chainWebpackMainProcess: (config) => {
// Chain webpack config for electron main process only
},
chainWebpackRendererProcess: (config) => {
// Chain webpack config for electron renderer process only
config.plugin('define').tap((args) => {
args[0]['IS_ELECTRON'] = true
return args
})
},
// Use this to change the entrypoint of your app's main process
mainProcessFile: 'src/background.js',
// Provide an array of files that, when changed, will recompile the main process and restart
Electron
// Your main process file will be added by default
//mainProcessWatch: ['src/myFile1', 'src/myFile2'],
// Provide a list of arguments that Electron will be launched with during "electron:serve",
// which can be accessed from the main process (src/background.js).
// Note that it is ignored when --debug flag is used with "electron:serve", as you must launch
Electron yourself
// Command line args (excluding --debug, --dashboard, and --headless) are passed to Electron
as well
//mainProcessArgs: ['--arg-name', 'arg-value']
}
}
}
// https://nklayman.github.io/vue-cli-plugin-electron-builder/guide/configuration.html#typescript-
options
module.exports = {
pluginOptions: {
electronBuilder: {
// option: default // description
disableMainProcessTypescript: false, // Manually disable typescript plugin for main process.
Enable if you want to use regular js for the main process (src/background.js by default).
mainProcessTypeChecking: false // Manually enable type checking during webpck bundling for
background file.
}
}
}
tsconfig.json :
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"experimentalDecorators": true,
"strictFunctionTypes": false,
"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"types": [
"webpack-env",
"mocha",
"chai"
],
"paths": {
"@/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx",
"main/**/*.ts"
],
"exclude": [
"node_modules"
]
}
I looked around, but didn't any working solution: as described here: Loading preload script in Electron and Vue
I added these lines in preload.js, but it didn't work:
window.onload = () => {
const { dialog } = require("electron").remote;
window.electron = {};
window.electron.dialog = dialog; // now set properly
};
I tried to follow the solution to the same problem but with React, instead of Vue.js, but I didn't succeed: https://github.com/electron/electron/issues/9920#issuecomment-336757899
Update 1)
I put preload.js into dist_electron folder :
(base) marco@pc01:~/webMatters/electronMatters/ggc-new/dist_electron$
ls -lah
total 1,5M
drwxr-xr-x 2 marco marco 4,0K ago 6 09:11 .
drwxr-xr-x 9 marco marco 4,0K ago 6 09:11 ..
-rw-r--r-- 1 marco marco 1,5M ago 5 23:25 index.js
-rw-r--r-- 1 marco marco 3,0K ago 5 23:22 package.json
-rw-r--r-- 1 marco marco 54 ago 5 22:06 preload.js
In background.ts I modified the path to preload.js :
declare const __dirname: string
win = new BrowserWindow({
webPreferences: {
nodeIntegration: false,
preload: path.join(__dirname, "../dist_electron/preload.js"),
}
}
I added the following lines to webpack.config.js :
const CopyPlugin = require('copy-webpack-plugin');
module.exports = {
plugins: [
new CopyPlugin({
patterns: [
{ from: 'source', to: 'dest' },
{ from: 'other', to: 'public' },
],
options: {
concurrency: 100,
},
}),
],
};
Executing yarn electron:serve I get this error:
And it seems that what I've done corresponds to what is suggested to do here: How to use preload.js properly in Electron
So... what am I missing? How to solve the problem?
Update 2)
As suggested here: https://github.com/electron/electron/issues/9920#issuecomment-575839738 and here https://github.com/reZach/secure-electron-template/blob/master/docs/secureapps.md to keep the app safer nodeIntegration has to be kept false, as it is already as default. And ìI would like to keep the app safer.
But anyway, I tried also to put nodeIntegration: true :
webPreferences: { nodeIntegration: true, preload: path.join(__dirname, "../dist_electron/preload.js"), }
And this is the output:
Marco