How to use jQuery in Firefox Extension
I use the following example.xul
:
<?xml version="1.0"?><overlay id="example" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"><head></head><script type="application/x-javascript" src="jquery.js"></script><script type="application/x-javascript" src="example.js"></script></overlay>
And here is an example.js
(function() { jQuery.noConflict(); $ = function(selector,context) { return new jQuery.fn.init(selector,context||example.doc); }; $.fn = $.prototype = jQuery.fn; example = new function(){}; example.log = function() { Firebug.Console.logFormatted(arguments,null,"log"); }; example.run = function(doc,aEvent) { // Check for website if (!doc.location.href.match(/^http:\/\/(.*\.)?stackoverflow\.com(\/.*)?$/i)) return; // Check if already loaded if (doc.getElementById("plugin-example")) return; // Setup this.win = aEvent.target.defaultView.wrappedJSObject; this.doc = doc; // Hello World this.main = main = $('<div id="plugin-example">').appendTo(doc.body).html('Example Loaded!'); main.css({ background:'#FFF',color:'#000',position:'absolute',top:0,left:0,padding:8 }); main.html(main.html() + ' - jQuery <b>' + $.fn.jquery + '</b>'); }; // Bind Plugin var delay = function(aEvent) { var doc = aEvent.originalTarget; setTimeout(function() { example.run(doc,aEvent); }, 1); }; var load = function() { gBrowser.addEventListener("DOMContentLoaded", delay, true); }; window.addEventListener("pageshow", load, false);})();
The following solution makes it possibile to use jQuery in contentScriptFile (Targetting 1.5 Addon-sdk)
In your main.js:
exports.main = function() { var pageMod = require("page-mod"); pageMod.PageMod({ include: "*", contentScriptWhen: 'end', contentScriptFile: [data.url("jquery-1.7.1-min.js") , data.url("notifier.js") , data.url("message.js")], onAttach: function onAttach(worker) { //show the message worker.postMessage("Hello World"); } });};
In your message.js :
self.on("message", function(message){ if(message !== "undefined"){ Notifier.info(message); }});
Some pitfalls you need to watchs out for:
- The order of the contentScriptFile array. if message.js would be placed first: jQuery won't be reconized.
- Do not place a http:// url in the data.url (this does not work)!
- All your javascript files should be in the data folder. (only main.js should be in lib folder)
There is an excellent article in the mozillaZine forums that describes this step-by-step: http://forums.mozillazine.org/viewtopic.php?f=19&t=2105087
I haven't tried it yet, though so I hesitate to duplicate the info here.