我正在尝试将我的 Google Chrome 扩展程序移植到 Firefox Add-On SDK,并且我需要该扩展程序来过滤我网站中的页面并进行重定向。例如,如果用户打开“http://example.com/special http://example.com/special“我需要把他送到”http://example.com/redirect 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
最好的方法是在较低级别进行:
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 中看到这段代码,请看一下这个插件 https://github.com/matagus/remove-google-redirects-addon/blob/master/lib/main.js (免责声明:这是我开发的一个插件)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)