javascript - Get a random url from chrome.bookmarks and load it in newTab -
this question has answer here:
i building chrome extension load random url bookmarks bar when open new tab.
my app.js has following code:
var bookmarksarray = []; // function traverse bookmarks tree , save urls in bookmarksarray function process_bookmark(bookmarks) { (var =0; < bookmarks.length; i++) { var bookmark = bookmarks[i]; if (bookmark.url) { bookmarksarray.push(bookmark.url); } if (bookmark.children) { process_bookmark(bookmark.children); } } } // process bookmarks of user function createbookmarksarray(){ chrome.bookmarks.gettree(process_bookmark); } // random bookmark url array , load function getbookmark(){ window.location.href = bookmarksarray[math.floor(math.random()*bookmarksarray.length)]; } // functions called on page load function onloadfunctions(){ createbookmarksarray(); getbookmark(); } // function run on page load document.addeventlistener("domcontentloaded", function(event) { onloadfunctions(); });
also manifest.json asks newtab , bookmarks permissions. newtab set index.html calls ap.js
when run extension, "your file not found. may have been moved or deleted.err_file_not_found" error.
when run window.location.href =bookmarksarray[math.floor(math.random()*bookmarksarray.length)];
in console, works fine.
am calling functions wrong?
all chrome api functions use callbacks. means when call createbookmarksarray
starts process of getting bookmarks, calls getbookmark
empty array.
chrome.bookmarks.gettree
asynchronous - when call starts process off, , callback called after has finished. js gives priority inline code, of current function complete before callback fired, if chrome able bookmarks instantly.
the best way avoid use async
, await
. chrome api doesn't support them directly, can use library chrome-extension-async
it.
then code looks this:
// function run on page load document.addeventlistener("domcontentloaded", async event => { try { // await tells js continue after callback has fired const bookmarktree = await chrome.bookmarks.gettree(); // flatten collection , grab 1 @ random const bookmarksarray = process_bookmark(bookmarktree); const randomindex = math.floor(math.random()*bookmarksarray.length); const randombookmark = bookmarksarray[randomindex]; // create new tab url await chrome.tabs.create({ url: randombookmark }); } catch(err){ // handle error in callbacks here } });
Comments
Post a Comment