SHARE
TWEET

Firefox SDK Callback Registry

surfcanyon Feb 19th, 2015 248 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //main.js - our background script
  2. var data = require("sdk/self").data;
  3. var tabs = require('sdk/tabs');
  4. var Requester = require("sdk/request");
  5. tabs.on('ready', function(tab) {
  6.  //Listens for "GET" messages from the content script
  7.  worker.port.on("GET", function(params) {
  8.   var req = new Requester.Request({
  9.    url: params.url,
  10.    onComplete: function (response) {
  11.     //get the key of the callback stashed on the content script,
  12.     //based on whether or not the request was successful
  13.     var callbackKey = (response.status == 200) ? params.sKey : params.errKey||null;
  14.  
  15.     //send a message back to the appropriate listener on the content script
  16.     worker.port.emit('ajaxResponse', {responseText: response.text,
  17.        callbackKey: callbackKey});
  18.    }
  19.   });
  20.   req.get();
  21.  });
  22. });
  23. //bootstrap.js - acts as a bridge between the background script and the content script
  24. (function() {
  25.  
  26.  // register callbacks that need to be executed on the
  27.  // response from the background script
  28.  var callbacks = {};
  29.  // Receives an AJAX response and a callback ID.
  30.  // Retrieves the callback via ID and executes it,
  31.  // passing the response as a parameter
  32.  self.port.on("ajaxResponse", function(response) {
  33.   if ((response.callbackKey) && callbacks[response.callbackKey]) {
  34.    //Retreive the callback and execute
  35.    callbacks[response.callbackKey](response);
  36.    delete callbacks[response.callbackKey];
  37.   }
  38.  });
  39.  
  40.  var smallRandom = function() {
  41.   return ('' + Math.random()).substring(2);
  42.  };
  43.  
  44.  AJAX = function(params) {
  45.   params.method = params.method||'GET';
  46.  
  47.   //in case method is defined, upper case it for
  48.   //consumption by the background API
  49.   params.method = params.method.toUpperCase();
  50.  
  51.   if (params.onerror) {
  52.    // make sure the key for the callback is fairly unique
  53.    var callbackKey = smallRandom();
  54.    callbacks[callbackKey] = params.onerror;
  55.    params.errKey = callbackKey;
  56.   }
  57.  
  58.   //Functions can't be passed to the background page.
  59.   //Register the callback, retrieve by key, then call
  60.   //so as not to lose its scope.
  61.   if (params.onload) {
  62.   // make sure the key for the callback is fairly unique
  63.    var callbackKey = smallRandom();
  64.    callbacks[callbackKey] = params.onload;
  65.    params.sKey = callbackKey;
  66.   }
  67.  
  68.   //now send the request message to the background script
  69.   self.port.emit(params.method, params);
  70.  }
  71. })();
RAW Paste Data
Top