Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save umamichi/5d52367235c98425e9d3fa4439d35046 to your computer and use it in GitHub Desktop.
Save umamichi/5d52367235c98425e9d3fa4439d35046 to your computer and use it in GitHub Desktop.
Electron で nodeIntegration: false にする方法

公式では、未来的に nodeIntegration: false にすることを推奨しています

理由は、レンダラプロセスで Node.js が実行できてしまうと、XSS発生時に脆弱性が増すためです

例えば、fs モジュールを使ってあなたのローカルファイルを取得して、どこかに送信することも可能ですし、ファイルを全て消し去ることもできてしまいます

nodeIntegration: false にする方法

Electronの設定

メインプロセスで nodeIntegration: false にする

 mainWindow = new BrowserWindow({
	...
    webPreferences: {
      // レンダラープロセスで Node.js 使えないようにする (XSS対策)
      nodeIntegration: false,
      // preloadスクリプトを, app.htmlとは別のJavaScriptコンテキストで実行するかどうか
      // false にしないと、window object を共有できない
      contextIsolation: false,
      // process や Electron を windowオブジェクト に保存する処理。フルパスの指定が必要
      preload: path.join(__dirname, '/preload.js'),
    },
    ...
  });
  

preload.js を用意

/**
 * preload.js
 * process や Electron を windowオブジェクト に保存する処理
 */
const electron = require('electron');

process.once('loaded', () => {
  // console.log('---- preload.js loaded ----');
  global.process = process;
  global.electron = electron;
  global.module = module;
});

global に持たせたものは、レンダラプロセスにて、window オブジェクトに入るので

require('electron')window.electron に書き換える

Webpackの設定

target: 'web' にする

もし、従来の方式である target:'electron-renderer' にしていた場合は、 bundle.js 内で require するコードが生成されるので、

Uncaught ReferenceError: require is not defined エラーが発生する

  entry: [
    ...
  ],

  output: {
    ...
  },

  /**
   * https://github.com/chentsulin/webpack-target-electron-renderer#how-this-module-works
   */
  target: 'web',
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment