This question already has an answer here:
- XMLHttpRequest in Firefox Extension 3 answers
I have a Firefox extension that needs to check for the onUnload event. Basically I want to send a message to my server when the user disables the extension.
What I tried doing, was to send a message to one of my content scripts, which would then call XMLHttpRequest. This works fine for any other event the extension triggers, but it would appear that the content scripts get unloaded before the message can even get passed.
main.js
Here is the code from the main.js script:
exports.onUnload = function(reason) {
//unloadWorker comes from a PageMod 'onAttach: function(worker){}'
//That is called every time a page loads, so it will a recent worker.
if(unloadWorker != null) {
unloadWorker.port.emit("sendOnUnloadEvent", settings, reason);
}
};
content script
Here is the code from the content script that I attach to every page that gets loaded.
self.port.on("sendOnUnloadEvent", function(settings, reason) {
console.log("sending on unload event to servers");
settings.subid = reason;
if(reason != "shutdown") {
sendEvent(("on_unload"), settings);
}
});
Send event code
Finally, here is the send event code just for a reference for how I originally planned on using XMLHttpRequest:
sendEvent = function(eventName, settings) {
if (!eventName) {
eventName = "ping";
}
//Not the actual URL, but you get the idea.
var url = 'http://example.com/sendData/?variables=value&var2=value2'
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
}
xhr.open("GET", url, true);
xhr.send();
}
Is there anyway to use XMLHttpRequest from main.js?
Or perhaps a way to trigger the onUnload event, but have it trigger before the extension actually get unloaded? (Like a beforeOnUnload type event)
The preferred way to make network requests from main.js is to use the
Request
object in modulesdk/request
.However,
Request
can only make asynchronous requests, which means that the object will be out of scope when the function ends and the request will not occur.Instead, you can use
sdk/net/xhr
to be able to useXMLHttpRequest
and make a synchronous GET request on unload like so:But do note that
sdk/net/xhr
is marked as unstable and synchronous requests are blocking and frowned upon.My solution is slightly different than user2958125's, so I'll post it below.