6

I'm attempting to create a simple example that would just alert the first 5 bookmark titles.

I took Google's example code and stripped out the search query to see if I could create a basic way to cycle through all Nodes. The following test code fails my alert test and I do not know why.

function dumpBookmarks() {
var bookmarkTreeNodes = chrome.bookmarks.getTree(
  function(bookmarkTreeNodes) {
   (dumpTreeNodes(bookmarkTreeNodes));
  });
}
function dumpTreeNodes(bookmarkNodes) {
var i;
for (i = 0; i < 5; i++) {
  (dumpNode(bookmarkNodes[i]));
}
}
function dumpNode(bookmarkNode) {
alert(bookmarkNode.title);
};

1 Answer 1

11

Just dump your bookmarkTreeNodes into the console and you will see right away what is the problem:

var bookmarkTreeNodes = chrome.bookmarks.getTree(
  function(bookmarkTreeNodes) {
   console.log(bookmarkTreeNodes);
  });
}

(to access the console go to chrome://extensions/ and click on background.html link)

As you would see a returned tree contains one root element with empty title. You would need to traverse its children to get to the actual bookmarks.

Simple bookmark traversal (just goes through all nodes):

function traverseBookmarks(bookmarkTreeNodes) {
    for(var i=0;i<bookmarkTreeNodes.length;i++) {
        console.log(bookmarkTreeNodes[i].title, bookmarkTreeNodes[i].url ? bookmarkTreeNodes[i].url : "[Folder]");

        if(bookmarkTreeNodes[i].children) {
            traverseBookmarks(bookmarkTreeNodes[i].children);
        } 

    }
}
5
  • How would I traverse the object as opposed to traversing the DOM? Not sure how to get around in there!
    – Korak
    Apr 6, 2011 at 20:53
  • @Korak What is your goal? What are you trying to find there?
    – serg
    Apr 6, 2011 at 21:01
  • What I'm ultimately looking to do is generate a selection list of folders from the tree for display/selection by a user. Thought I should start by just figuring out how asynchronous functions are set up just to pull a bit of data and have been stumped by it! (grrr)
    – Korak
    Apr 6, 2011 at 21:10
  • @Korak Well, tree(graph) structures are tricky to work with. I added example of how to traverse through all nodes. You just need to decide in which order you want to traverse it and go from there.
    – serg
    Apr 6, 2011 at 21:47
  • Thanks for the help! I'm going to work with your example and keep struggling along. Really appreciate it!
    – Korak
    Apr 7, 2011 at 1:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.