Pregunta

I am learning how to build Firefox Add-ons using the addon-sdk (jetpack). On the initial examples there is a very clear way of accessing the tab objects for all open tabs

var widget = require("sdk/widget").Widget({
  id: "mozilla-link",
  label: "Mozilla website",
  contentURL: "http://www.mozilla.org/favicon.ico",
  onClick: listTabs
});

function listTabs() {
  var tabs = require("sdk/tabs");
  for each (var tab in tabs)
    console.log(tab.url);
}

And from there I can add listeners and such. What I really want is to access the history of each tab and take a look of what page was before it or what page is after it (if it exists).

I have been going trough the documentation and I have learned of the BFCache but I have not come up with any clear way of getting the history of an specific tab. What am I missing?

¿Fue útil?

Solución

The Tab instances returned by the tabs module don't allow us to do such advanced stuff, so it is necessary to get access to the XUL tab object associated with the Add-on SDK tab. Ideally this would be provided to us as a property (xultab anyone?). Since this is not the case we have to improvise.

The id property of the Add-on SDK tab enables the tracking of the associated XUL tab. Once we have that, the session history of the tab is at hand.

const { getTabs, getTabId, getBrowserForTab } = require('sdk/tabs/utils');
const { activeTab } = require('sdk/tabs');

function getXULTabFromId(id){
  var tabs = getTabs();
  return tabs.find(function(tab){
    return id == getTabId(tab) ? true : false;
  });
}

// Assuming the following code runs inside the onclick handler of a widget

var xultab = getXULTabFromId(activeTab.id);
var browser = getBrowserForTab(xultab);
var sessionHistory = browser.webNavigation.sessionHistory;
var count = sessionHistory.count;

for(var i = 0; i < count; i++){
  var entry = sessionHistory.getEntryAtIndex(i, false);
  if(sessionHistory.index == i) console.log('***');
  console.log(entry.title + ' - ' + entry.URI.spec);
  if(sessionHistory.index == i) console.log('***')
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top