Skip to content

Instantly share code, notes, and snippets.

@tritonrc
Created November 15, 2009 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tritonrc/235502 to your computer and use it in GitHub Desktop.
Save tritonrc/235502 to your computer and use it in GitHub Desktop.
Javascript XPCOM Long-poll Singleton
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
var gLongPollInstance = null;
function LongPoll() {
if(gLongPollInstance)
return gLongPollInstance;
gLongPollInstance = this;
this.wrappedJSObject = this;
this.observerService =
Components.classes["@mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
this.timer = null;
this.endpoint = "http://notifications.example.com";
this.currentRequest =
Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Components.interfaces.nsIXMLHttpRequest);
this.currentRequest.mozBackgroundRequest = true;
this.currentRequest.onreadystatechange = function(evt) {
if (gLongPollInstance.currentRequest.readyState == 4) {
var status = gLongPollInstance.currentRequest.status;
var timeout = 5000;
if(status >= 200 && status < 300) {
gLongPollInstance.observerService.notifyObservers(
null,
'longpoll',
'{"topic":"notification", "data":' + gLongPollInstance.currentRequest.responseText +'}');
} else {
timeout = 60000;
}
gLongPollInstance.timer =
Components.classes["@mozilla.org/timer;1"]
.createInstance(Components.interfaces.nsITimer);
gLongPollInstance.timer.init(
gLongPollInstance,
timeout,
Components.interfaces.nsITimer.TYPE_ONE_SHOT);
}
};
}
LongPoll.prototype = {
classDescription: "Long-Poll Component",
classID: Components.ID("{1C0E8E86-A661-40D0-AE3D-ABCDEFABCDEF}"),
contractID: "@example.com/longpoll;1",
QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsISupports]),
setEndpoint: function(nPoint) {
this.endpoint = nDomain;
this.currentRequest.abort();
},
poll: function() {
this.currentRequest.open('GET', this.endpoint, true);
this.currentRequest.send(null);
},
observe: function(subject, topic, data) {
switch(topic) {
case 'timer-callback':
this.poll();
break;
}
}
};
var components = [LongPoll];
function NSGetModule(compMgr, fileSpec) {
return XPCOMUtils.generateModule(components);
}
@ED8506
Copy link

ED8506 commented Aug 5, 2020

classID: Components.ID("{e6b866e3-41b2-4f05-a4d2-3d4bde0f7ef8}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment