Ways to verify distinct elements within chrome.storage array

In my quest to develop an array stored in chrome.sync that holds the URLs of unique pages visited by a user, I have encountered a hurdle. Adding URLs to the array is not problematic, but determining whether a URL already exists within the array is proving to be a challenge. Here is my current approach:

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

The code functions properly when I eliminate the map functionality and only retain:

           array.push(tabUrl);
           chrome.storage.sync.set({data: array}, function() {
               console.log("added")
           });

Strangely, when inspecting the array using dev tools, no errors are found - just an empty data array. However, upon right-clicking on the extension's popup, I receive the following error message:

Error handling response: TypeError: Cannot read properties of undefined (reading 'url') at chrome-extension://jkhpfndgmiimdbmjbajgdnmgembbkmgf/getURL.js:31:30

That line 31 in getURL.js? It pertains to retrieving the active tab, like so:

let tabUrl = tabs[0].url;

This issue is compounded by the fact that this line is part of a separate function entirely.

Answer №1

One way to solve this is by utilizing the includes method:

function addArr(tabUrl, array) {
  if (!array.includes(tabUrl)) {
    array.push(tabUrl);
    chrome.storage.sync.set({data: array});
  }
}

Nevertheless, it's important to keep in mind that chrome.storage.sync has a limitation of 8192 bytes for each value, allowing approximately only 100 URLs within the array. To work around this, you can limit the number of elements in the array using methods such as array.splice, utilize multiple keys in the storage, or switch to chrome.storage.local. Additionally, there are various restrictions in the sync storage, including limits on write operations frequency which may be exceeded with high user navigation activity. For a more efficient solution, consider using IndexedDB where each URL serves as a separate key, eliminating the need to rewrite the entire array with each update.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking for a script that automatically swaps out a div at set intervals? You'll need to tweak it so that it only

I created a js script that dynamically changes the content of certain div elements at specified intervals. While I appreciate how it functions, I now need to modify it so that the script only executes once. Can someone help me achieve this? <script typ ...

Utilizing an array to cycle through various images

Initially, I'm facing an issue with morscreens[i] not displaying the desired image from the array. When left as it is, it ends up showing a [<] button followed by "morscreens[i]" and then a [>] button. However, enclosing morscreens[i] in quotes ...

Guide to redirecting data from an external POST request to a customer through a GET request

Within my Express application, I am currently dealing with both incoming POST requests containing a payload from an external source and GET requests sent by my client: router.post('/liveReleaseStore', (req, res) => { let data = req.body.m ...

Avoid using recursive functions with nested arrays to prevent complexity and potential

In the code snippet below, the function $data is comprised of objects/arrays that represent data extracted from a database: public function build_tree($data, $parent_id = '0') { $tree = array(); foreach ($data as $key => $value) { ...

Whenever I attempt to execute yarn build within next.js, an error always seems to occur

When attempting to compile my next.js project using the yarn build command, an error consistently occurs: Error: Export encountered errors on following paths: /settings at D:\web3\futnft\frontend\node_modules\next\ ...

Update the style class of an <img> element using AJAX

My success with AJAX enables PHP execution upon image click. However, I seek a real-time visual representation without page reload. Thus, I aim to alter <img> tag classes on click. Presently, my image tag resembles something like <img title="< ...

Isolating Express.js Requests for Enhanced Security

In my Node.js Express app, multiple users send requests to the server for various actions such as earning points, changing email addresses, and interacting with other users. My server code utilizes several setTimeouts, leading me to question whether diffe ...

Top 5 Benefits of Utilizing Props over Directly Accessing Parent Data in Vue

When working with VueJS, I've noticed different approaches to accessing parent properties from a component. For example, let's say I need to utilize the parent property items in my component. Option One In this method, the component has a props ...

The API response is indicating that it is empty, however, upon further examination, it is not

I created an API that shows a user's followers and following users. Everything is displaying correctly on the screen. However, when I try to use console.log() to display the array it is stored in after calling the method, it shows as an empty array. I ...

Creating a Node API that can patiently listen for external data

My current project involves building a server that fetches data from an external API and returns it to the endpoint localhost:3000/v1/api/. However, I'm facing a challenge where the data retrieval process takes approximately 2 seconds, leading to empt ...

Is there a way to display various data with an onClick event without overwriting the existing render?

In the process of developing a text-based RPG using React/Context API/UseReducer, I wanted to hone my skills with useState in order to showcase objects from an onclick event. So far, I've succeeded in displaying an object from an array based on button ...

The error message "Uncaught (in promise) ReferenceError: dispatch is not defined" indicates that

Currently, I am utilizing vuex with index.js and auth.js stored in the store folder. My goal is to perform a basic sign-in operation within my signin.vue by calling an action from the store. However, I encountered the error 'Uncaught (in promise) Refe ...

Adjusting the speed of Flexslider with mousewheel control

I am looking to implement flexslider with mousewheel functionality. Here is an example of how I want it to work: $('#slider').flexslider({ animation: "slide", mousewheel: true, direction: "vertical", ...

I've noticed that my alert is not appearing when I click submit. Can someone please help me figure out what I could

I am having trouble getting my alert to display when the form is not validating. It should show an alert message if the form is valid but it's not working as expected. I've spent hours trying to fix this issue with no luck. I appreciate any help ...

Adding icons to form fields based on the accuracy of the inputs provided

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Assignment 2 - Website Bui ...

"Utilize jQuery to create a new row when an image button is clicked

I am looking for a way to duplicate the existing <tr> every time I click on the + button, represented by <i class="fa fa-plus" aria-hidden="true"></i> Here is the structure of my <tr>. How can I achieve this using jQuery or JavaScr ...

React - ensuring only one child component is "active" at a time

I have a main component that contains several child components. My goal is to apply an active class to a child component when it is clicked on. The current setup is functioning properly, however, the problem lies in the fact that multiple child components ...

Removing a Dom element using stage.removeChild( )

When the number 6 is typed and entered into the game, the function correct() in the code snippet below determines what action to take. I would like to remove the DOM element gg (the equation 3+3=input) from the stage after typing 6 and pressing enter. How ...

Struggling to update a scope variable when utilizing Firebase's Facebook authentication with AngularJS

Hey there... I'm currently exploring AngularJS and attempting to implement Facebook's connect feature using Firebird. Almost everything is running smoothly - the connection to my Facebook account is successful, and the information is retrieved w ...

The expiry date of the cookie remains unchanged

When attempting to create a cookie and specify an expiration date, I am encountering an issue where it remains as "Session". This problem is occurring in Google Chrome. I'm looking for insights on what might be causing this behavior. The code snippe ...