1

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:

enter image description here

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:

enter image description here

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:

enter image description here

Marco

user2315094
  • 759
  • 3
  • 16
  • 29
  • Marco, as I said. After the build, the preload.js is not in dist_electron – tpikachu Aug 05 '20 at 17:46
  • @tpikachu I guess I'm missing something. If after the build, the preload.is not in dist_electron, what should I do? Where should I then place preload.js? – user2315094 Aug 05 '20 at 19:46
  • Well, of course. The preload.js should be in dis_electron – tpikachu Aug 06 '20 at 00:52
  • So, I'd suggest to you try place preload in dist_electron as temporary – tpikachu Aug 06 '20 at 00:52
  • And if this works, you can configure this on your webpack configuration – tpikachu Aug 06 '20 at 00:52
  • https://webpack.js.org/plugins/copy-webpack-plugin/ – tpikachu Aug 06 '20 at 00:53
  • @tpikachu I modifies my question above with Update 1 – user2315094 Aug 06 '20 at 07:24
  • man, you are setting this as false. `nodeIntegration: false` – tpikachu Aug 06 '20 at 09:33
  • @tpikachu I would like to keep the app safer 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, keeping the default value of nodeIntegration: false. But I tried also with nodeIntegration: true, and gives error. I updated my question above with update 2 – user2315094 Aug 06 '20 at 09:41
  • 1
    What is the github repo? If this is open source I'll have a look at this – tpikachu Aug 06 '20 at 09:42
  • Thank you very much @tpikachu. At the moment I'm not able to put it in github repo. But I will do it within the next very few hours. – user2315094 Aug 06 '20 at 09:45
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/219359/discussion-between-user2315094-and-tpikachu). – user2315094 Aug 06 '20 at 17:59
  • @tpikachu You were right: putting preload.js in dist_electron is correct. May I ask you to give a look at another electron.js problem I encountered? https://stackoverflow.com/questions/63343205/ipcrenderer-onsetting-event-any-args-any-causes-this-error-dirn – user2315094 Aug 10 '20 at 15:45

0 Answers0