Search code examples
javascriptnode-webkitnw.jsnwjs

jquery not working in nw.js (node webkit)


I am switching my desktop app from electron to nw.js because of source code security features.

I am requiring the module jquery-confirm in my nodejs file, I get this error:

Uncaught Error: jquery-confirm requires jQuery

I fix this error by:

var $ = require('jquery');
window.jQuery = $;
var jconfirm = require('jquery-confirm');

and importing the js file in index.html like this:

<script>require('./bot.js')</script>

Becuase I get the same jquery error if I require the js file like:

<script src="bot.js"></script>

When I fix the error like above and I launch the app with nw.js, it immediately crashes giving this error:

TypeError: $(...).button is not a function

First question: I am assuming there is something wrong with jquery. When I import it in index.html, it doesnt work at all. However, I am still running into issues after requiring it in the js file. How can I fix this?

Second question: Why dont I get the Uncaught Error: jquery-confirm requires jQuery error if I import my js file using 'require' instead of ?


Solution

  • This is an issue of javascript context in Node Webkit. We must ensure all the javascript required inside the browser (the window context) is brought into that context by using the src attribute of a script tag.

    Node Webkit places JavaScript from require() statements in the nodejs global context - and makes it unavailable inside the browser.

    So we see errors such as $ is not defined or $(...).button() is not a function if files are in opposite contexts.