-->

How to change script location on firefox addon?

2020-07-24 03:57发布

问题:

What is the simplest way to make the firefox addon, which repeats this chrome functionality:

chrome.webRequest.onBeforeRequest.addListener(
  function(info) {
    if(info.url.indexOf("notifier") + 1){
        return {redirectUrl: "https://domain.null/1.js"};
    }

  },
  {
    urls: [
      "*://domain2.null/*"
    ],
    types: ["script"]
  }, ["blocking"]);

I know about nsIContentPolicy in firefox, but I don't understand how to use it.

All opinions, advice, and help will be appreciated

Answer

I've determined the problem with the restartless extension.
To block content we can use nsIContentPolicy as Wladimir said. We also can inject script to page with windowListener (aWindow.gBrowser).

For example, this practice works perfectly: https://github.com/jvillalobos/AMO-Admin-Assistant/blob/master/src/bootstrap.js

回答1:

I don't think that this can be done without major hacks right now. This is subject of bug 765934 that will add a redirectTo() method to the nsIHttpChannel interface. Once it is implemented code like this should work:

const Ci = Components.interfaces;
const Cu = Components.utils;

Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");

var observer = {
  QueryInterface: XPCOMUtils.generateQI([
    Ci.nsIObserver,
    Ci.nsISupportsWeakReference
  ]),

  observe: function(subject, topic, data)
  {
    if (topic == "http-on-modify-request" &&
        subject instanceof Ci.nsIHttpChannel)
    {
      var uri = subject.URI;
      if (uri.host == "domain2.null" && /\.js(\?|$)/.test(uri.path))
      {
        var redirectUri = Services.io.newURI("https://domain.null/1.js",
                                             null, null);
        subject.redirectTo(redirectUri);
      }
    }
  }
};

Services.obs.addObserver(observer, "http-on-modify-request", true);

For reference: Services.jsm, XPCOMUtils.jsm, observer notifications, nsIHttpChannel, nsIURI