我正在实施Firefox插件。在插件的工具栏中,我捕获了当前页面,并在用户尝试转到荷兰Google时将其重定向到UK Google。但是,此代码需要永远完成。当我输入“ google.nl”或“ google.com/nl”时,我的浏览器将显示荷兰页面,并至少需要1秒钟才能重定向。
有什么方法可以使重定向更快?理想情况下,我希望用户完全不要看到荷兰Google页面。
function loadURL(url) {
window._content.document.location = url;
window.content.focus();
}
var redirected = false;
function onChange()
{
var url = gBrowser.selectedBrowser.currentURI.spec;
url = encodeURIComponent(url);
if(url.indexOf("google.nl") !=-1 || url.indexOf("hl%3Dnl") !=-1){
if (!redirected){
redirected = true;
loadURL("https://www.google.co.uk/");
return;
}
}else{
redirected = false;
}
}
注意:
onChange()
由container.addEventListener('DOMSubtreeModified',onChange, false);
触发 最佳答案
第一次观察
永远不要使用应该被删除的DOMSubtreeModified
。您应该使用MutationEvent
因此,以您的情况代替MutationObserver
来执行此操作:
const gMutationConfig = {
subtree: true,
childList: true
};
var gMutationFunc = function(ms) {
for (let m of ms) {
console.log(m.type, m);
//if (mutation.addedNodes && mutation.addedNodes.length > 0) { //this test if elements added
onChange();
}
};
var gMutationObserver = new this.DOMWindow.MutationObserver(container);
第二件事是
您可能应该使用
container.addEventListener('DOMSubtreeModified, onChange, false);
进行最快的重定向const { Ci, Cu, Cc, Cr } = require('chrome'); //const {interfaces: Ci, utils: Cu, classes: Cc, results: Cr } = Components;
Cu.import('resource://gre/modules/Services.jsm');
Cu.import('resource://gre/modules/devtools/Console.jsm');
var observers = {
'http-on-modify-request': {
observe: function (aSubject, aTopic, aData) {
console.info('http-on-modify-request: aSubject = ' + aSubject + ' | aTopic = ' + aTopic + ' | aData = ' + aData);
var httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel);
var requestUrl = httpChannel.URI.spec
if (requestUrl.indexOf('google.com') > -1) {
//httpChannel.cancel(Cr.NS_BINDING_ABORTED); //this aborts the load
httpChannel.redirectTo(Services.io.newURI('data:text,url_blocked', null, null)); //can redirect with this line, if dont want to redirect and just block, then uncomment this line and comment out line above (line 17)
}
},
reg: function () {
Services.obs.addObserver(observers['http-on-modify-request'], 'http-on-modify-request', false);
},
unreg: function () {
Services.obs.removeObserver(observers['http-on-modify-request'], 'http-on-modify-request');
}
}
};
开始观察
要开始观察所有请求,请执行此操作(例如,在启动插件时)
for (var o in observers) {
observers[o].reg();
}
停止观察
停止观察很重要(确保至少在插件关闭时运行此命令,由于内存原因,您不想让观察者注册)
for (var o in observers) {
observers[o].unreg();
}
用于阻止/重定向URL的观察器服务的完整工作示例:https://github.com/Noitidart/PortableTester/tree/block-urls
关于javascript - 为什么此JavaScript页面重定向如此之慢?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25327282/