问题
I'm trying to port my Google Chrome extension to Firefox Add-On SDK and I need the extension to filter pages from my website and make redirects. For example, if the user opens "http://example.com/special" I need to send him to "http://example.com/redirect" in the same browser tab.
This is how I tried to do this:
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";
}
}
});
Problem is: my browser hangs sometimes after the redirect (immediately after the new page has been displayed in a tab). What am I doing wrong?
Using Firefox 16.0.2, Add-On SDK 1.11
回答1:
The best way will be to do it at the lower level:
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);
};
If you want to see this code in actiton, take a look at this addon (DISCLAIMER: it's an addon I developed).
来源:https://stackoverflow.com/questions/13200058/how-to-make-a-redirect-in-firefox-page-mod