How to make a redirect in Firefox page-mod?

牧云@^-^@ 提交于 2019-12-21 17:56:35

问题


I'm trying to port my Google Chrome extension to Firefox Add-On SDK and I need the extension to filter pages from my website and make redirects. For example, if the user opens "http://example.com/special" I need to send him to "http://example.com/redirect" in the same browser tab.

This is how I tried to do this:

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

Problem is: my browser hangs sometimes after the redirect (immediately after the new page has been displayed in a tab). What am I doing wrong?

Using Firefox 16.0.2, Add-On SDK 1.11


回答1:


The best way will be to do it at the lower level:

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

If you want to see this code in actiton, take a look at this addon (DISCLAIMER: it's an addon I developed).



来源:https://stackoverflow.com/questions/13200058/how-to-make-a-redirect-in-firefox-page-mod

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