Chrome Bookmarks API -

荒凉一梦 提交于 2021-02-05 18:57:02

问题


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:


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

    }
}


来源:https://stackoverflow.com/questions/5570760/chrome-bookmarks-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!