Fast way to redirect tab when new page is loading

白昼怎懂夜的黑 提交于 2020-01-05 10:24:34

问题


I'm trying to redirect a tab to a new page when the URL matches my pattern before it's done loading. The method I came up with does the redirection after a good part of the page is done loading yet.

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);

Is there a good way of calling setTabURL (...) earlier?


回答1:


I finally found the best way to do it:

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: answer by matagus (on question asked by Andrew)

[1]: Link: Intercepting Page Loads
[2]: Noitidart: 'from topics: How can I change the User Agent in just one tab of Firefox? and Is it possible to know the target DOMWindow for an HTTPRequest?'




回答2:


Never used sdk/tabs before, but you could load your content hidden.

Once your page has loaded your logShow function will run.

Then build into this function some "reveal body" functionality.



来源:https://stackoverflow.com/questions/24849385/fast-way-to-redirect-tab-when-new-page-is-loading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!