Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

154
141

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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オプションを使って制御するのがよさそう。

154
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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
154
141

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?