Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't "chrome.bookmarks.getTree" work?

If I try the following code:

chrome.bookmarks.getTree(function(items) {
  items.forEach(function(item) {
    document.write(item.url);
  });
});

it returns undifined. But when I write:

chrome.bookmarks.getRecent(20, function(items) {
  items.forEach(function(item) {
    document.write(item.url);
  });
});

it works.

Why does it differ?

like image 367
Tom Avatar asked Apr 22 '12 14:04

Tom


1 Answers

Both chrome.bookmarks.getTree and chrome.bookmarks.getRecent return an array of BookmarkTreeNodes, but BookmarkTreeNodes do not necessarily have a url property. In the case of getTree, the top nodes of the tree are folders and do not have URLs:

BookmarkTreeNode structure

If you use getTree, you'll have to traverse the tree recursively using each node's children array. It helps to know that every BookmarkTreeNode either has a children attribute (if it's a folder) or a url attribute (if it's an actual bookmark). Try something like:

chrome.bookmarks.getTree(function(itemTree){
    itemTree.forEach(function(item){
        processNode(item);
    });
});

function processNode(node) {
    // recursively process child nodes
    if(node.children) {
        node.children.forEach(function(child) { processNode(child); });
    }

    // print leaf nodes URLs to console
    if(node.url) { console.log(node.url); }
}
like image 171
apsillers Avatar answered Nov 04 '22 05:11

apsillers