351

Problem: while developing using Electron, when you try to use any JS plugin that requires jQuery, the plugin doesn't find jQuery, even if you load in the correct path using script tags.

For example,

<body>
<p id="click-me">Click me!</p>
...
<script src="node_modules/jquery/dist/jquery.min.js"></script> //jQuery should be loaded now
<script>$("#click-me").click(() => {alert("Clicked")});</script>
</body>

Running this code above wouldn't work. In fact, open up DevTools, go to the Console view, and click on the <p> element. You should see that function $ is not defined or something to that effect.

Pranav A.
  • 460
  • 1
  • 5
  • 18
Bruno Vaz
  • 4,992
  • 6
  • 17
  • 27

21 Answers21

844

A better and more generic solution IMO:

<!-- Insert this line above script imports  -->
<script>if (typeof module === 'object') {window.module = module; module = undefined;}</script>

<!-- normal script imports etc  -->
<script src="scripts/jquery.min.js"></script>    
<script src="scripts/vendor.js"></script>    

<!-- Insert this line after script imports -->
<script>if (window.module) module = window.module;</script>

Benefits

  • Works for both browser and electron with the same code
  • Fixes issues for ALL 3rd-party libraries (not just jQuery) without having to specify each one
  • Script Build / Pack Friendly (i.e. Grunt / Gulp all scripts into vendor.js)
  • Does NOT require node-integration to be false

source here

codemirror
  • 3,164
  • 29
  • 42
Dale
  • 8,772
  • 1
  • 15
  • 15
  • actually this is not electron problem it is the new standard since a lot of client side libraries now is trying to support both require() and html load , anyway you can also load jquery in your app using – Fareed Alnamrouti Jul 20 '16 at 05:57
  • 1
    @fareednamrouti Yes, but the point of this solution was that you don't have to list the 3rd party libraries (it just works!). Handy when you are importing many libraries (or self bundled scripts) – Dale Aug 15 '16 at 01:47
  • 2
    thanks! in my case, this solution also works for older versions of d3 like d3 v3 or below – headwinds Oct 05 '16 at 18:57
  • 3
    @DaleHarders It turns out `window.module` begins with the same value as `module`, so your code doesn't work quite as expected. The proper way to do it is to save `module` to some other (unused) window property instead, like `window.tempModule`. To confirm what I say, try `console.log(module)` after your last statement to verify that now `module === undefined`. – Lucio Paiva Nov 05 '16 at 23:15
  • 2
    @Lucio Nope. We need to save to window.module as this is where the 3rd party libraries are expecting it (browser environment). I think you're confusing Node.js and browser environments. This trick is to aid in development so your code can run in the browser AND node/electron without any additional configuration. There are many other ways to do it but this is simplest IMHO. – Dale Dec 04 '16 at 05:59
  • 1
    This is problematic with CSP—no inline scripts – Trevor Mar 20 '18 at 04:35
  • After searching all over, this worked like a charm. ++1 – Nuwan Jayawardene Apr 07 '20 at 17:09
  • Nice! Can you add comments to explain what the code is doing to make it work? – yanike Apr 27 '20 at 17:27
130

As seen in https://github.com/atom/electron/issues/254 the problem is caused because of this code:

if ( typeof module === "object" && typeof module.exports === "object" ) {
  // set jQuery in `module`
} else {
  // set jQuery in `window`
}

The jQuery code "sees" that its running in a CommonJS environment and ignores window.

The solution is really easy, instead of loading jQuery through <script src="...">, you should load like this:

<script>window.$ = window.jQuery = require('./path/to/jquery');</script>

Note: the dot before the path is required, since it indicates that it's the current directory. Also, remember to load jQuery before loading any other plugin that depends on it.

Adam Harte
  • 10,369
  • 7
  • 52
  • 85
Bruno Vaz
  • 4,992
  • 6
  • 17
  • 27
  • 1
    Thanks, but I have a system created by yeoman with angular. Grunt takes all my bower dependencies and build them into a vendor.js file. How can I load jquery, fix with your line, and continue with the other bower dependencies that needs jquery? – bluesky777 Oct 07 '15 at 23:10
  • I don't understand, the vendor.js have jquery inside? If so, you could load the vendor.js with this window.$ method, afaik. – Bruno Vaz Oct 10 '15 at 02:01
  • Some comments later in the linked issue there is an even better solution: `'node-integration': false` as option for `BrowserWindow`. – Boldewyn Dec 17 '15 at 15:55
  • 8
    Doesn't this affect other things? – Bruno Vaz Dec 18 '15 at 16:57
57

Another way of writing <script>window.$ = window.jQuery = require('./path/to/jquery');</script> is :

<script src="./path/to/jquery" onload="window.$ = window.jQuery = module.exports;"></script>
Aaleks
  • 4,283
  • 5
  • 31
  • 39
56

electron FAQ answer :

http://electron.atom.io/docs/faq/

I can not use jQuery/RequireJS/Meteor/AngularJS in Electron.

Due to the Node.js integration of Electron, there are some extra symbols inserted into the DOM like module, exports, require. This causes problems for some libraries since they want to insert the symbols with the same names.

To solve this, you can turn off node integration in Electron:

// In the main process.

let win = new BrowserWindow({  
 webPreferences: {
 nodeIntegration: false   } });

But if you want to keep the abilities of using Node.js and Electron APIs, you have to rename the symbols in the page before including other libraries:

<head> 
<script> 
window.nodeRequire = require; 
delete window.require;
delete window.exports; delete window.module; 
</script> 
<script type="text/javascript" src="jquery.js"></script> 
</head>
Fran6
  • 591
  • 4
  • 3
37

Just came across this same problem

npm install jquery --save

<script>window.$ = window.jQuery = require('jquery');</script>

worked for me

Dhaval Chauhan
  • 8,777
  • 1
  • 17
  • 17
  • This is exactly what my original answer says. – Bruno Vaz Oct 09 '16 at 19:04
  • Hi how to do same with materialize.min.js https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/js/materialize.min.js . .. something like this ??? can someone help – Makjb lh Apr 24 '17 at 13:33
22

You can put node-integration: false inside options on BrowserWindow.

eg: window = new BrowserWindow({'node-integration': false});

Cethy
  • 1,552
  • 2
  • 15
  • 22
Murilo Feres
  • 229
  • 2
  • 4
14

A nice and clean solution

  1. Install jQuery using npm. (npm install jquery --save)
  2. Use it: <script> let $ = require("jquery") </script>
Tassu
  • 215
  • 3
  • 13
adgelbfish
  • 354
  • 2
  • 15
9

I face the same issue and this worked for me!

Install jQuery using npm

$ npm install jquery

Then include jQuery in one of the following ways.

Using script tag

<script>window.$ = window.jQuery = require('jquery');</script>

Using Babel

import $ from 'jquery';

Using Webpack

const $ = require('jquery');
Abraham
  • 8,525
  • 5
  • 47
  • 53
6
<script>
  delete window.module;
</script>

before your jquery import and you're good to go. more info here.

Sagiv Ofek
  • 25,190
  • 8
  • 60
  • 55
5

I think i understand your struggle i solved it little bit differently.I used script loader for my js file which is including jquery.Script loader takes your js file and attaching it to top of your vendor.js file it did the magic for me.

https://www.npmjs.com/package/script-loader

after installing the script loader add this into your boot or application file.

import 'script!path/your-file.js';

Mertcan Diken
  • 14,483
  • 2
  • 26
  • 33
5

Just install Jquery with following command.

npm install --save jquery

After that Please put belew line in js file which you want to use Jquery

let $ = require('jquery')
Milan Hirpara
  • 166
  • 1
  • 9
4

ok, here's another option, if you want a relative include...

<script> window.$ = window.jQuery = require('./assets/scripts/jquery-3.2.1.min.js') </script>
aestrro
  • 963
  • 10
  • 10
3

If you are using Angular2 you can create a new js file with this code:

// jquery-electron.js

if ((!window.jQuery || !window.$) && (!!module && !!module.exports)) {
      window.jQuery = window.$ = module.exports;
}

and put it right after jquery path, in .angular-cli.json:

"scripts": [
    "../node_modules/jquery/dist/jquery.js",
    "assets/js/jquery-electron.js",
    ...
    ...
]
Max
  • 319
  • 2
  • 9
3

im building and Angular App with electron, my solution was the following:

index.html

<script>
    if ( typeof module === "object" && typeof module.exports === "object" ) {
      window.$ = window.jQuery = require('jquery');
    }
</script>

angular.json

"scripts": [
              "node_modules/jquery/dist/jquery.min.js",
              "node_modules/popper.js/dist/umd/popper.min.js",
              "node_modules/bootstrap/dist/js/bootstrap.min.js"
            ]

So Jquery gets loaded from angular.json if on browser, else if it is an electron builded app it will require module instead.

If you want to import jquery in index.html instead of importing from angular.json use the following solution:

<script src="path/to/jquery"></script>
<script>
    if ( typeof module === "object" && typeof module.exports === "object" ) {
      window.$ = window.jQuery = require('jquery');
    }
</script>
Kuza Grave
  • 1,256
  • 14
  • 15
2

worked for me using the following code

var $ = require('jquery')
Adeojo Emmanuel IMM
  • 2,104
  • 1
  • 19
  • 28
2

1.Install jQuery using npm.

npm install jquery --save

2.

<!--firstly try to load jquery as browser-->
<script src="./jquery-3.3.1.min.js"></script>
<!--if first not work. load using require()-->
<script>
  if (typeof jQuery == "undefined"){window.$ = window.jQuery = require('jquery');}
</script>
2

This works for me.

<script languange="JavaScript">
     if (typeof module === 'object') {window.module = module; module = undefined;}
</script>

Things to consider:

1) Put this in section right before </head>

2) Include Jquery.min.js or Jquery.js right before the </body> tag

Lithilion
  • 1,097
  • 2
  • 11
  • 26
1

For this issue, Use JQuery and other js same as you are using in Web Page. However, Electron has node integration so it will not find your js objects. You have to set module = undefined until your js objects are loaded properly. See below example

<!-- Insert this line above local script tags  -->
<script>if (typeof module === 'object') {window.module = module; module = 
undefined;}</script>

<!-- normal script imports etc  -->
<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>    

<!-- Insert this line after script tags -->
<script>if (window.module) module = window.module;</script>

After importing like given, you will be able to use the JQuery and other things in electron.

Kiran Maniya
  • 8,453
  • 9
  • 58
  • 81
1

Well in 2022. This worked for me.

Install JQuery

npm install jquery --save

Use the script tag to add jquery to your index.html file. The src should be the path to jquery in your node_modules folder

    <script type="text/javascript" src="../node_modules/jquery/dist/jquery.min.js"></script>

Now JQuery would be available/defined as $ in your renderer process (renderer.js file)

michael_vons
  • 875
  • 1
  • 8
  • 16
0

you may try the following code:

mainWindow = new BrowserWindow({
        webPreferences: {
            nodeIntegration:false,
        }
});
shuoGG
  • 19
  • 1
  • In my case, this is the one that works. Or you can do just by simply remove/comment out/ the line that says `nodeIntegration: true`. – Aryo Oct 20 '20 at 13:57
0

Install jquery using yarn

yarn add jquery
Syamdas
  • 11
  • 5