Question

I have read the many posts on this matter and tried all the ways to include jQuery.

If I load the jQuery in the xul file and store it in a variable it works. (as in How to use jQuery in Firefox Extension)

jQuery.noConflict();
sbsh.safeWalletUtils.$ = function (selector, context) {
    return new jQuery.fn.init(selector, context || doc);
};
sbsh.safeWalletUtils.$.fn = sbsh.safeWalletUtils.$.prototype = jQuery.fn;

However, I suspect that the suggest solution here is much better: http://forums.mozillazine.org/viewtopic.php?f=19&t=2105087

loadjQuery: function(wnd){
  var loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
 .getService(Components.interfaces.mozIJSSubScriptLoader);
  loader.loadSubScript("chrome://clhelper/content/jquery/jquery-1.5.js",wnd);
  var jQuery = wnd.jQuery.noConflict(true);
  loader.loadSubScript("chrome://clhelper/content/jquery/jquery.hoverIntent.js", jQuery);
  return jQuery;
 },

in Page Load event handler:

var doc = event.originalTarget;
var wnd = doc.defaultView;
// load jQuery and save it as a property of the window
myprivatejQuery = loadjQuery(wnd)

However I keep getting wnd.jQuery undefined..(few people in the link also said that was the problem)

What should I do? How do I use jQuery and not worry about conflict inside a Firefox extension?

Was it helpful?

Solution

After more investigation, and thanks to Omri Baumer for he relentless work..

We now understand why we get the error.

The right way to do it is not in the xul file as an include (as I suspected) but via calling the unwrapped js object:

// correct function to load jQuery
var loadjQuery = function(wnd){
  var loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
   .getService(Components.interfaces.mozIJSSubScriptLoader);
   loader.loadSubScript("chrome://sbshsafewallet/content/jquery-1.8.3.js", wnd);
   var jQuery = XPCNativeWrapper.unwrap(wnd).$;
   jQuery.noConflict(true);
  return jQuery;
};


// field to store the jQuery for the current document window (as there can be multiple tabs)
var jQueryForWindow = null;

// event to call on window load (didn't include the code, left for reader to do)
windowLoad = function (event)
{
    var appcontent = document.getElementById("appcontent"); // browser  
    appcontent.addEventListener("DOMContentLoaded", pageLoadedInit, false);
}

// load jQuery on DOMContentLoaded event
pageLoad = function (event) {
      var doc = event.originalTarget;
      var wnd = doc.defaultView;
      jQueryForWindow = loadjQuery(wnd);
}


//example of function using the jQuery
function usesjQuery()
{
   var $ = jQueryForWindow;
   //do something with jquery here
}

Hope this helps all of you that have been stuck!!

Thanks again to Omri Baumer!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top