Tom
Tom

Reputation: 794

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?

Upvotes: 6

Views: 4979

Answers (3)

Juan Guillermo
Juan Guillermo

Reputation: 31

Before modifying your code try this!

Check if the extension has the persimo 'bookmarks'. You can see it in chrome://extensions/, 'Details' button, 'Permissions' section.

If it doesn't say 'Read and change favorites', then delete the Chrome extension and reload it unpackaged.

In my case, I loaded the extension and worked on it, updating it to incorporate the changes, then I realized that I hadn't requested the 'bookmarks' permission in the manifest.json, so I added it and updated the extension. Then chrome.bookmarks gave me 'undefined'.

It took me more than a couple of hours to realize that the manifest.json is not updated when you update the extension, it is only updated when you delete and reupload the extension.

D'oh!

Upvotes: 0

Chris
Chris

Reputation: 1

chrome.bookmarks needs permission to use. Try to use it in page chrome://bookmarks.

Upvotes: -2

apsillers
apsillers

Reputation: 116040

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); }
}

Upvotes: 10

Related Questions