我正在尝试将我的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
答案 0 :(得分: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中查看此代码,请查看this addon(免责声明:这是我开发的插件)。