Suvarna Pattayil
Suvarna Pattayil

Reputation: 5239

Firefox Extension page-mod onAtttach is slow

I am using Firefox Add-on SDK to build an extension to capture URL entered by the user as soon as possible. Since, I didn't find anything in tabs API [ found load, activate etc. ] which will give me asap access to the URL I am using page-mod.

I have observed that incase of very fast redirects onAttach is not able to capture the intial few URLs because the redirects are very fast.

index.js

var pageMod = require("sdk/page-mod");

pageMod.PageMod({

include: ['*'], 
contentScriptWhen: 'start', 
contentScriptFile: data.url("mycontscript.js"),
attachTo: "top", 
onAttach: function(worker) {
  var tabUrl = worker.tab.url;
  console.log('User typed ' + tabUrl);
  ... Interact with content script ...
  }
  ...
});

How can I capture the intial URLs, or is there another API which can help me with my actual intention of the extension. Please note I am not talking about interaction with my content script. The console.log prints after a couple of redirects are done basically missing the intial ones.

Upvotes: 0

Views: 64

Answers (2)

Judas Iscariot
Judas Iscariot

Reputation: 83

/*
 * contentScriptWhen: "start"
 *
 * "start": Load content scripts immediately after the document
 * element is inserted into the DOM, but before the DOM content
 * itself has been loaded
 */

/*
 * use an empty HTMLElement as a way to prevent
 * the DOM content from loading
 */
document.replaceChild(
    document.createElement("html"), document.children[0]);

/*
 * do whatever you want here
 */

/* then reload the current page from the server */
document.location.reload(true);

Upvotes: 0

Bryan Clark
Bryan Clark

Reputation: 2602

PageMod or the tabs API aren't built to see HTTP redirects, I'm guessing that's what you mean by very fast redirects. Both of those APIs require a valid page load before emitting an event about the action so you wouldn't get the values a person types into the URL bar.

If you wanted to capture what URLs were typed into the URL bar you could look into the places event system. Places is the database that handles all of Firefox history and bookmarks so the history events will be triggered when a new page is entered into the URL bar or navigated to via a link.

Here's some code to get you started:

const { events } = require('sdk/places/events');
// https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsINavHistoryService#Transition_type_constants
const TRANSITION_REDIRECT_PERMANENT = 5;
const TRANSITION_REDIRECT_TEMPORARY = 6;

events.on('data', function({type, data}) {
  if (type === 'history-visit') {
      if (data.transitionType === TRANSITION_REDIRECT_PERMANENT ||
          data.transitionType === TRANSITION_REDIRECT_TEMPORARY) {
        console.log('redirect');
      }
    console.log(data.url);
  }
})

Upvotes: 2

Related Questions