Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //main.js - our background script
- var data = require("sdk/self").data;
- var tabs = require('sdk/tabs');
- var Requester = require("sdk/request");
- tabs.on('ready', function(tab) {
- //Listens for "GET" messages from the content script
- worker.port.on("GET", function(params) {
- var req = new Requester.Request({
- url: params.url,
- onComplete: function (response) {
- //get the key of the callback stashed on the content script,
- //based on whether or not the request was successful
- var callbackKey = (response.status == 200) ? params.sKey : params.errKey||null;
- //send a message back to the appropriate listener on the content script
- worker.port.emit('ajaxResponse', {responseText: response.text,
- callbackKey: callbackKey});
- }
- });
- req.get();
- });
- });
- //bootstrap.js - acts as a bridge between the background script and the content script
- (function() {
- // register callbacks that need to be executed on the
- // response from the background script
- var callbacks = {};
- // Receives an AJAX response and a callback ID.
- // Retrieves the callback via ID and executes it,
- // passing the response as a parameter
- self.port.on("ajaxResponse", function(response) {
- if ((response.callbackKey) && callbacks[response.callbackKey]) {
- //Retreive the callback and execute
- callbacks[response.callbackKey](response);
- delete callbacks[response.callbackKey];
- }
- });
- var smallRandom = function() {
- return ('' + Math.random()).substring(2);
- };
- AJAX = function(params) {
- params.method = params.method||'GET';
- //in case method is defined, upper case it for
- //consumption by the background API
- params.method = params.method.toUpperCase();
- if (params.onerror) {
- // make sure the key for the callback is fairly unique
- var callbackKey = smallRandom();
- callbacks[callbackKey] = params.onerror;
- params.errKey = callbackKey;
- }
- //Functions can't be passed to the background page.
- //Register the callback, retrieve by key, then call
- //so as not to lose its scope.
- if (params.onload) {
- // make sure the key for the callback is fairly unique
- var callbackKey = smallRandom();
- callbacks[callbackKey] = params.onload;
- params.sKey = callbackKey;
- }
- //now send the request message to the background script
- self.port.emit(params.method, params);
- }
- })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement