0

我正在構建Firefox的附加組件,如果URL匹配某些條件,則會將請求重定向到新URL。我試過這個,但它不起作用。使用HTTP-on-modify-request重定向URL

我在HTTP-on-modify-request上註冊了一個觀察者來處理URL,如果URL匹配我的條件,我將重定向到一個新的URL。

這裏是我的代碼:

var Cc = Components.classes; 
var Ci = Components.interfaces; 
var Cr = Components.results; 

var newUrl = "https://google.com"; 

function isInBlacklist(url) { 
// here will be somemore condition, I just use youtube.com to test 
    if (url.indexOf('youtube.com') != -1) { 
     return true; 
    } 
    return false; 
} 

exports.main = function(options,callbacks) { 
// Create observer 
httpRequestObserver = 
{ 
    observe: function (subject, topic, data) { 
     if (topic == "http-on-modify-request") { 
      var httpChannel = subject.QueryInterface(Ci.nsIHttpChannel); 
      var uri = httpChannel.URI; 
      var domainLoc = uri.host; 

      if (isInBlacklist(domainLoc) === true) { 
       httpChannel.cancel(Cr.NS_BINDING_ABORTED); 
       var gBrowser = utils.getMostRecentBrowserWindow().gBrowser; 
       var domWin = channel.notificationCallbacks.getInterface(Ci.nsIDOMWindow); 
       var browser = gBrowser.getBrowserForDocument(domWin.top.document); 
       browser.loadURI(newUrl); 
      } 
     } 
    }, 

    register: function() { 
     var observerService = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService); 
     observerService.addObserver(this, "http-on-modify-request", false); 
    }, 

    unregister: function() { 
     var observerService = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService); 
     observerService.removeObserver(this, "http-on-modify-request"); 
    } 
}; 
//register observer 
httpRequestObserver.register(); 
}; 

exports.onUnload = function(reason) { 
    httpRequestObserver.unregister(); 
}; 

我是新來的Firefox插件開發。

回答

2

您可以撥打nsIHttpChannel.redirectTo來重定向頻道。 這是不可能的,一旦渠道被打開,但在http-on-modify-request它將工作。因此,在你的代碼

,你可以這樣做:

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

if (condition) { 
    httpChannel.redirectTo(
    Services.io.newURI("http://example.org/", null, null)); 
} 

它看起來像你可能會使用Add-on SDK來開發。在這種情況下,請閱讀Using Chrome Authority

0

你可以簡單地做,而不是

httpChannel.URI.spec = newUrl; 

httpChannel.cancel(Cr.NS_BINDING_ABORTED); 
... 
browser.loadURI(newUrl); 

不知道它是如何「安全」是你的情況,因爲我不完全知道如何在對方頭當您在此階段將URL更改爲指向完全不同的域時,請求(例如Cookie)將被操縱。