I am trying to create an array that is stored in chrome.sync
which contains the urls of all unique pages a user visits. Adding the url to the array works fine - what I am struggling with is how to check if that url already exists in the array. This is what I have currently:
function getURL(array) {
chrome.tabs.query({active: true, lastFocusedWindow: true, currentWindow: true}, tabs => {
let tabUrl = tabs[0].url;
addArr(tabUrl, array);
});
}
function addArr(tabUrl, array) {
array.map((x) => {
let urlCheck = x.url;
console.log(urlCheck);
if(urlCheck != tabUrl) {
array.push(tabUrl);
chrome.storage.sync.set({data: array}, function() {
console.log("added")
});
}
})
}
It works when I remove anything to do with the map and only keep the:
array.push(tabUrl);
chrome.storage.sync.set({data: array}, function() {
console.log("added")
});
This makes even less sense because when use dev tools to inspect the array, there is no error only an empty data array. The error that it gives me, however, when I inspect the popup (actually right click on extension) is
Error handling response: TypeError: Cannot read properties of undefined (reading 'url') at chrome-extension://jkhpfndgmiimdbmjbajgdnmgembbkmgf/getURL.js:31:30
That getURL.js line 31? That is part of the code that gets the active tab. i.e
let tabUrl = tabs[0].url;
which isn't even in the same function.
Use includes
method:
function addArr(tabUrl, array) {
if (!array.includes(tabUrl)) {
array.push(tabUrl);
chrome.storage.sync.set({data: array});
}
}
However, chrome.storage.sync has a limit of 8192 bytes for each value which can only hold in the ballpark of 100 URLs, so you'll have to limit the amount of elements in the array e.g. by using array.splice
or use several keys in the storage or use chrome.storage.local
. There are also other limits in the sync
storage like the frequency of write operations, which you can easily exceed if the user does a lot of navigation. An even better solution is to use IndexedDB with each URL as a separate key so you don't have to rewrite the entire array each time.