Search code examples
javascriptgoogle-chrome-extensionbookmarks

Chrome Extension - Bookmark 2 returning as undefined


I'm creating a chrome extension that allows navigation to the users first four bookmarks using ctrl+shift+number; everything is going well, and functional for the 1st, 3rd and 4th bookmark, but the 2nd bookmark seemingly returns undefined every time. I have a feeling this is due to the way that I'm navigating the bookmark tree that is get from the chrome api, but I'm unsure where or how I can fix this at all. Another thought is that this function has to be resolved asynchronously, but I'm unsure why that would be, or why it would work with the other bookmarks if that is the case.

This is my js file

const bookmarks = [];

chrome.tabs.onCreated.addListener(function(tab) { //refresh bookmarks on new tab opening
    var bookmarkTreeNodes = chrome.bookmarks.getTree(
    function(bookmarkTreeNodes){
        bookmarksArray(bookmarkTreeNodes)
    })
})

chrome.commands.onCommand.addListener(function(command){ 
    var bookmarkTreeNodes = chrome.bookmarks.getTree( //also check bookmarks on command execution
        function(bookmarkTreeNodes){
            bookmarksArray(bookmarkTreeNodes)
        })
    printArray(); //temp
    console.log('command:',command.charAt(8)); //tab number temp 
    tabSelected = command.charAt(8);
    chrome.tabs.update({
        url: ("" + bookmarks[tabSelected-1])
    })    
});

function printArray(){
    for(var i = 0; i<bookmarks.length; i++){
        console.log(bookmarks[i]);
    }
}
    
function bookmarksArray(bookmarkTree){
    for(var i=0; i<bookmarkTree.length; i++){
        bookmarks[i] = ("" + bookmarkTree[i].url); //url is insert to each spot as string 
        console.log("" + bookmarks[i])
        if(bookmarkTree[i].children){
            bookmarksArray(bookmarkTree[i].children)
        }
    }
}

Solution

  • You're ovwrwriting the same elements of bookmarks in the recursive calls to bookmarksArray(), since each loop starts at 0. Use push() to append to the array instead of writing to the same indexes as in bookmarkTree.

    function bookmarksArray(bookmarkTree) {
      for (var i = 0; i < bookmarkTree.length; i++) {
        bookmarks.push(String(bookmarkTree[i].url));
        console.log(bookmarks[i])
        if (bookmarkTree[i].children) {
          bookmarksArray(bookmarkTree[i].children)
        }
      }
    }