3
votes

Currently I use addon sdk to develop a firefox extension,which can redirect some request without loading them.

For example, a page refer a.js (maybe have something like this <script src='example.com/a.js'>), then, I want to redirect this request to example2.com/b.js

Now,with nsIContentPolicy I can block example.com/a.js,

But I don't know how to load example2.com/b.js at the time when a.js is blocked.

my codes now look like this:

const { Cc, Ci } = require("chrome");
const xpcom = require("sdk/platform/xpcom");
const { Class } = require("sdk/core/heritage");

exports.gcleaner = Class({
  extends: xpcom.Unknown,
  interfaces: ["nsIContentPolicy"],
  shouldLoad: function (contType, contLoc, reqOrig, ctx, typeGuess, extra) {
  //https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIContentPolicy#shouldLoad()   
    if (contType === 2)  //2 means js 
    {   
        var blockReg = new RegExp('example.com/a.js');
        if (contLoc['spec'].match(blockReg)) 
        {
            return Ci.nsIContentPolicy.REJECT;
        };

    };  
    return Ci.nsIContentPolicy.ACCEPT;
  },  

  shouldProcess: function (contType, contLoc, reqOrig, ctx, mimeType, extra) {
    return Ci.nsIContentPolicy.ACCEPT;
  }
});

let factory = xpcom.Factory({
  Component:   exports.gcleaner,
  description: "hello world",
  contract:    "@liujiacai.net/gcleaner"
});

var catman = Cc["@mozilla.org/categorymanager;1"].getService(Ci.nsICategoryManager);
catman.addCategoryEntry("content-policy", "speeding.gcleaner", factory.contract, false, true);

Thanks!

1
See "Second thing" in this solution here: stackoverflow.com/a/25328750/1828637 - Noitidart
Hi @Noitidart, before I use your "second thing", I have to ACCEPT all request in nsIContentPolicy. If I reject a request, then no redirect happen for it don't request it at all. Then I remove nsIContentPolicy code, Well it can actually redirect a url,but the original url still load. Can you deal with this? - Jiacai Liu

1 Answers