LoginSignup
155
141

More than 5 years have passed since last update.

ElectronでjQueryがundefinedになる

Last updated at Posted at 2015-06-05

ElectronでjQueryがundefinedになる。

index.html
<body>
    <script src="lib/jquery.min.js"></script>
    <script>
        jQuery('#hoge'); // jQuery is not defined
    </script>
</body>

原因

electronのissueがあった。

jQuery isn't set globally because "module" is defined · Issue #254 · atom/electron

Electronではブラウザ側のJS実行時にmodule.exportsが存在するので、jQueryがcommonJSでロードされたと勘違いして、windowに$とjQueryを定義しないというのが原因。(この辺りにif文が

解決策

requireでロードする

<!--<script src="lib/jquery.js"></script>-->
<script>
window.jQuery = window.$ = require('./lib/jquery');
</script>

上記のようにrequireでロードしてwindow.$, window.jQueryに代入する。

'node-integration': false

メインプロセス側JSでBrowserWindowをインスタンス化する時のオプションに'node-integration': falseを追加する。

main-process.js
// In the main process.
const {BrowserWindow} = require('electron')
let win = new BrowserWindow({
  webPreferences: {
    nodeIntegration: false
  }
})
win.show()

そうすると、ブラウザ側にmodule.exportsが定義されなくなるので、ブラウザ側JSを修正する必要がない。

基本的にはBrowserifyやWebpackなどを使ってCommonJSで開発して、アプリのWebViewみたいにElectron外のWebページを表示させたい場合はnode-integrationオプションを使って制御するのがよさそう。

155
141
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
155
141