To extract the domains from the URLs of all tabs we need to create an A element in the main.js file of our add-on:
function listTabs() {
var tabs = require("sdk/tabs");
for each (var tab in tabs)
{
var tab_url = document.createElement('a');
tab_url.href = tab.url;
var domain[] = tab_url.hostname;
}
However we get an error "document not defined". We also tried content.document but this also didn't work.
(I know that there are other ways to extract the domain but from compatibility reasons this is the only way that our add-on should do it).
Hope someone can help.
Cheers
I don't really understand what you're trying to do so here's two different approaches.
If you need access to the document element of a page you're going to have to use a more low level approach unless you want to simplify and just use a page-mod
.
Here's how you'd create an A element on pages within tabs:
var { getTabs, getTabContentWindow } = require('sdk/tabs/utils');
function listTabs1() {
var tabs = getTabs();
tabs.forEach(function (tab) {
// Fake a newly created document
var window = getTabContentWindow(tab);
var document = window.document;
var tab_url = document.createElement('a');
tab_url.setAttribute("href", tab.url);
});
}
I'd suggest using a page-mod
to do this page altering instead of the above code.
But if you're just looking to examine the host of each tab you can just loop through them like you did and then use the URL
module to do the difficult hostname parsing.
var URL = require('sdk/url').URL;
var tabs = require("sdk/tabs");
function listTabs2() {
tabs.forEach(function (tab) {
var url = URL(tab.url);
console.log(url.hostname);
});
}
And just a final tip is that you could easily write a module that uses the nsIEffectiveTLDService
for finding the top level domain of the host name you believe you have since all that parsing of URLs is prone to error. https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIEffectiveTLDService
Good luck!