Running Add-on Code at First Run (and Upgrade)

Running code when your add-on is first installed or upgraded is pretty common. You might need to install a toolbar button or display a web page. I’ve seen a few different ways to do this, so I thought I’d show how I do it in my add-ons.

The best way to demonstrate this is with some sample code. I’ll make some comments on at the end.

The Firefox 4 Add-on Bar for Developers

As I mentioned last week, my posts will be a mix of Firefox add-on posts and personal posts. This one is about Firefox add-ons.

One of the new features in Firefox 4 is the add-on bar. Love it or hate it, as an add-on developer, you’re going to have to get used to it. I recently ported one of my add-ons that has a status bar icon over to use the add-on bar, so I thought I would share the experience. This post assumes that you have built a Firefox add-on before and are porting it over to Firefox 4.

POSTing Multipart/Form-Data from an XMLHttpRequest

I’m working on an add-on where I have a need to POST JSON data to the server. Unfortunately that JSON contains ampersands, so in order to use POST, I would have to encode the data in some way that the server could decode. This seemed like extra unnecessary work to me. I decided to use the “multipart/form-data” header which would allow me to send the data unmodified. Unfortunately, documentation on this was lacking. So this post is just to put up sample code on how to do this in case someone else needs it. In this case, I am simply passing data=foo where foo is the JSON.

var xhr = Components.classes[";1"].createInstance(Components.interfaces.nsIXMLHttpRequest);"POST", url, true);

var boundary = '---------------------------';
boundary += Math.floor(Math.random()*32768);
boundary += Math.floor(Math.random()*32768);
boundary += Math.floor(Math.random()*32768);
xhr.setRequestHeader("Content-Type", 'multipart/form-data; boundary=' + boundary);
var body = '';
body += '--' + boundary + '\r\n' + 'Content-Disposition: form-data; name="';
body += "data";
body += '"\r\n\r\n';
body += JSON.stringify(JAVASCRIPT OBJECT);
body += '\r\n'
body += '--' + boundary + '--';
xhr.setRequestHeader('Content-length', body.length);
xhr.onload = function() {

There were no server changes required at all. The PHP handled the data the same way it would have if it was an “application/x-www-form-urlencoded” POST.

Belorussian provided by Patricia