简体   繁体   English

Chrome 扩展 - 书签 2 返回未定义

[英]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;我正在创建一个 chrome 扩展,允许使用 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.我有一种感觉,这是由于我导航从 chrome api 获取的书签树的方式,但我不确定在哪里或如何解决这个问题。 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这是我的 js 文件

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

You're ovwrwriting the same elements of bookmarks in the recursive calls to bookmarksArray() , since each loop starts at 0 .您在对bookmarksArray()的递归调用中编写相同的bookmarks元素,因为每个循环都从0开始。 Use push() to append to the array instead of writing to the same indexes as in bookmarkTree .使用push()追加到数组,而不是写入与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) } } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM