加载新页面时快速重定向选项卡的方法

Fast way to redirect tab when new page is loading

本文关键字:选项 方法 重定向 新页面 加载      更新时间:2023-09-26

我试图重定向一个选项卡到一个新的页面,当URL匹配我的模式之前它完成加载。我提出的方法是在页面的大部分完成加载后进行重定向。

var tabs = require("sdk/tabs");
var tab_utils = require("sdk/tabs/utils");
function logShow(tab) {
    console.log(tab.url + " is loaded; " + pattern.test(tab.url));
    if (pattern.test(tab.url)) {
        var lowLevelTab = viewFor(tab);
        console.log(tab_utils.setTabURL (lowLevelTab, newURL(tab.url)));
        // also simply replacing this bit with
        // tab.url = "foo" doesn't speed things up
    }
}
tabs.on('load', logShow);

是否有更早调用setTabURL (...)的好方法?

最后找到了最好的方法:

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.
    if (pattern.test(url)) {
        // If you want to redirect to another url,
        // you have to abort current request, see: [1] (links below)
        channel.cancel(Cr.NS_BINDING_ABORTED);
        // Set the current gbrowser object (since
        // the user may have several windows/tabs)
        var goodies = loadContextGoodies(channel);
        var domWin = goodies.aDOMWindow;       // method suggested by
        var gBrowser = goodies.gBrowser;       // Noitidart [2] (links below)
        var browser = goodies.browser;         // for reference see comment below
        var htmlWindow = goodies.contentWindow;
        // and load the fixed URI
        browser.loadURI(newUrl(url));
    } else {
        // do nothing, let Firefox keep going on the normal flow
    }
}
exports.main = function() {
    events.on("http-on-modify-request", listener);
}

credit where credit is due: matagus回答Andrew的问题

[1]:链接:拦截页面加载
[2]: Noitidart: 'from topics:如何在Firefox的一个选项卡中更改用户代理?是否有可能知道一个HTTPRequest的目标DOMWindow ?'

以前从未使用过sdk/tabs,但是您可以隐藏加载您的内容。

一旦你的页面加载你的logShow函数将运行。

然后在这个函数中构建一些"显示主体"的功能。