Search code examples
javascriptfirefox-addonfirefox-addon-sdk

Save URLs on current page in addon sdk with document.links


Is it possible to save all URLs on current page to a variable using Mozilla addon sdk?

contentScript: 'self.on("click", function () {' +

    'var data=new Object();' +
    'data.selectedText = window.getSelection().toString();' +
    'data.links = document.links;' +

    '  self.postMessage(data);' +
    '});',
onMessage: function (data) {

    console.log(data.selectedText);
    console.log(data.links.length);
}

Output

info: addon: hello
info: addon: undefined

Solution

  • data.links = document.links doesn't work, as document.links returns a node collection of DOM anchor Elements, that cannot be serialized as JSON (as messages need to be).

    However, what should work is:

    data.links = Array.map(document.links, function(l) l.href);
    

    This would map the collection to a new Array containing the link target URIs as strings, and strings can be serialized.