httpChannel.redirectTo()无限加载

时间:2014-07-19 08:55:18

标签: javascript firefox redirect firefox-addon

我第一次使用firefox扩展程序,感谢文档,它的速度非常快。 但是我遇到了一个问题:如果用户进入某些域名,我就不会重定向用户。

const {Cc, Ci, Cr, Cu} = require("chrome");
const buttons = require('sdk/ui/button/action');
const tabs = require("sdk/tabs");



var httpRequestObserver =
{
  observe: function(subject, topic, data)
  {
    if (topic == "http-on-modify-request") {
    var httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);
    var eTLDService = Cc["@mozilla.org/network/effective-tld-service;1"].getService(Ci.nsIEffectiveTLDService);
    var suffix = eTLDService.getPublicSuffixFromHost(httpChannel.originalURI.host);
    var regexp = new RegExp('google\.'+suffix,'i');
    if (regexp.test(httpChannel.originalURI.host)) {
            Cu.import("resource://gre/modules/Services.jsm");
            httpChannel.redirectTo(Services.io.newURI("http://test.tld", null, null));
        }


     }



  get observerService() {
    return Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
  },

  register: function()
  {
    this.observerService.addObserver(this, "http-on-modify-request", false);
  },

  unregister: function()
  {
    this.observerService.removeObserver(this, "http-on-modify-request");
  }
};

httpRequestObserver.register();

我试图做一点POC,但它似乎无限期地加载。

你知道我做错了吗?

1 个答案:

答案 0 :(得分:2)

不要测试originalURI!它将保持the same even after a redirect

/**
 * The original URI used to construct the channel. This is used in
 * the case of a redirect or URI "resolution" (e.g. resolving a
 * resource: URI to a file: URI) so that the original pre-redirect
 * URI can still be obtained. ...
 */

所以你重定向,创建了一个新的频道,其中相同 originalURIURI不同,所以你的测试会一次又一次地触发......导致无限重定向循环(并且通过此API重定向也不受通常的重定向限制)。

而是测试频道的.URI,它会提供当前 URI。