How to redirect in a Firefox page?

I am trying to port the Google Chrome extension to the Firefox Add-On SDK, and I need an extension to filter pages from my site and redirect. For example, if a user opens " http://example.com/special " I need to send him to " http://example.com/redirect " on the same browser tab.

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

The problem is that my browser sometimes freezes after a redirect (right after a new page has been displayed on a tab). What am I doing wrong?

Using Firefox 16.0.2, Add-On SDK 1.11

+4
source share
1 answer

The best way is to do it at a 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, check out this addon ( DISCLAIMER: the addon I developed).

+4
source

Source: https://habr.com/ru/post/1443700/


All Articles