4

我正在尝试将我的 Google Chrome 扩展程序移植到 Firefox Add-On SDK,我需要该扩展程序来过滤我网站中的页面并进行重定向。例如,如果用户打开“ http://example.com/special ”,我需要将他发送到同一浏览器选项卡中的“ http://example.com/redirect ”。

这就是我尝试这样做的方式:

var pageMod = require("page-mod").PageMod({
    include: "*",
    contentScriptWhen: "start",
    contentScript: "",

    onAttach: function(worker) {
       if (worker.tab.url == worker.url && 
           worker.url.indexOf("example.com/special") > -1) {
           worker.tab.url = "http://example.com/redirect";
       }
    }
});

问题是:我的浏览器在重定向后有时会挂起(在新页面显示在选项卡中之后立即)。我究竟做错了什么?

使用 Firefox 16.0.2,附加 SDK 1.11

4

1 回答 1

4

最好的方法是在较低级别进行:

const { Cc, Ci, Cr } = require("chrome");

var events = require("sdk/system/events");
var utils = require("sdk/window/utils");


function listener(event) {
    var channel = event.subject.QueryInterface(Ci.nsIHttpChannel);
    var url = event.subject.URI.spec;

    // Here you should evaluate the url and decide if make a redirect or not.
    // Notice that "shouldIredirect" and "newUrl" are guessed objects you must replace!
    if (shouldIredirect) {
      // If you want to redirect to another url, the you have to abort current request
      // See https://developer.mozilla.org/en-US/docs/XUL/School_tutorial/Intercepting_Page_Loads
      channel.cancel(Cr.NS_BINDING_ABORTED);

      // Aet the current gbrowser object (since the user may have several windows and tabs) and load the fixed URI
      var gBrowser = utils.getMostRecentBrowserWindow().gBrowser;
      var domWin = channel.notificationCallbacks.getInterface(Ci.nsIDOMWindow);
      var browser = gBrowser.getBrowserForDocument(domWin.top.document);

      browser.loadURI(newUrl);
    } else {
      // do nothing, let Firefox keep going on the normal flow
    }
  };
};

exports.main = function() {
  events.on("http-on-modify-request", listener);
};

如果您想在 actiton 中查看此代码,请查看此插件免责声明:这是我开发的插件)。

于 2014-02-18T01:46:11.980 回答