Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use jQuery 1.5.2+ on a Firefox addon?

At first I made a function that received a parameter and returned jQuery such as:

function getjQuery(window)
{
   /*jquery code*/(window);
   return window.jQuery;
}

But then I got an email form the review and they told me I have to use jQuery file with the original file name and completely unmodified.

I started to search for an alternative and found this solution, but there is no way it work.

jQuery object is created, but I can't find any elements. $("#id").length is always 0. With the previous method it was always found.

My current code (which doesn't work)

AddonNameSpace.jQueryAux = jQuery;

AddonNameSpace.$ = function(selector,context) { 
    return                                                 // correct window
        new AddonNameSpace.jQueryAux.fn.init(selector,context||contentWindow); 
};
AddonNameSpace.$.fn =
    AddonNameSpace.$.prototype = AddonNameSpace.jQueryAux.fn;
AddonNameSpace.jQuery = AddonNameSpace.$;

The jQuery file is loading on my browser.xul overlay:

<script type="text/javascript" src="chrome://addon/content/bin/jquery-1.5.2.min.js" />

Am I loading in the right place?

How can I use jQuery to modify the content on a page (HTML) with the original jQuery file, is it even possible?

like image 237
BrunoLM Avatar asked May 02 '11 23:05

BrunoLM


1 Answers

You need pass the e.originalTarget.defaultView on the second parameter on jquery.. If you don't jquery will use window.document, which is the window.document from the xul.

Use

gBrowser.addEventListener("DOMContentLoaded", function (e) {
    $("#id", e.originalTarget.defaultView).length
}, true);

instead of

$("#id").length;

And, for avoid conflicts with other extensions don't use script in the xul page, use MozIJSSubScriptLoader.

Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
.getService(Components.interfaces.mozIJSSubScriptLoader)
.loadSubScript("chrome://youraddon/content/jquery-1.5.2.min.js"); 

If you use this method, you load jquery only when you need, avoiding memory leak.

like image 173
StiveKnx Avatar answered Sep 23 '22 17:09

StiveKnx