Save information to chrome's storage system

I have the need to save favorite and deleted IDs in my database. I created two functions for this purpose:

function ADD_BLOCKED(id) {
    chrome.storage.local.get("blocked", function (data) {
        if (data.blocked == null)
            data.blocked = [];

        if (!data.blocked.includes(id)) {
            data.deleted.push(id);
            chrome.storage.local.set(data);
        }

    });
}

function ADD_FAVORITE(id) {
    chrome.storage.local.get("favorite", function (data) {
        if (data.favorite == null)
            data.favorite = [];

        if (!data.favorite.includes(id)) {
            data.deleted.push(id);
            chrome.storage.local.set(data);
        }
    });
}

Is there a way to consolidate these functions? It's challenging to pass data.blocked as a parameter.

Answer №1

Utilize the parameter to take advantage of JavaScript's capabilities;

function add_to_storage(container, id) {
  chrome.storage.local.get(container, function(data) {
    // items can be accessed using bracket notation
    if (data[container] == null)
      data[container] = [];


    if (!data[container].includes(id)) {
      data.deleted.push(id);
      chrome.storage.local.set(data);
    }

  });
}

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

Ways to Modify the Additional Text with AngularJS

I'm encountering difficulties with the append event when adding each name from a single input field instead of using ng-repeat. Can anyone provide guidance on how to achieve this without relying on ng-repeat? Unfortunately, ng-repeat is not functionin ...

Click event not functioning correctly in Internet Explorer

When using jQuery, I have the following code: <script type="text/javascript"> $(document).ready(function(){ $('body').on('click', '.add-photo',function() { $("#images").append($('<input/>').attr(&apo ...

Prevent multer from uploading files if the field is left blank

Is there a way to prevent multer from attempting to upload a file if a specific field is left blank in a post request for users to update their profile? For example, if a user only wants to update their bio and not their profile picture. Here's the c ...

I understand the reason behind the unexpected { token error, but I'm unsure of how to resolve it when my PHP script needs to transmit a collection of data to JavaScript

I am currently utilizing this JavaScript fetch code to retrieve data from PHP async sendRequest(selectValue=this.selectValue){ const fetchResponse = await fetch('/server/getLastWords.php?select='+selectValue); const fetchJSON = await fe ...

Triggering a sweet alert on a mouse click

Here is a code snippet I found on . It shows an alert box that doesn't disappear when clicked outside of it. swal({ title: "Are you sure?", text: "You will not be able to recover this imaginary file!", type: "warning", showCancelButton: true, ...

"Implementing a self-invoking function in JavaScript and effectively clearing the interval within it

I am looking to stop the animation interval in this particular example $.fn.bounce = function(options) { var settings = $.extend({ speed: 10 }, options); return $(this).each(function() { var $this = $(this), $pa ...

Enhance Your Images with Fancybox 2.1.5 by Adding Titles Directly to the Photo Window

I need help figuring out how to place the title text inside the photo box on this particular page: Despite my efforts and multiple Google searches, I have not been successful in achieving this. As a newcomer to javascript, I am struggling with implementin ...

What makes using setInterval with a self-invoking function a smarter choice?

I recently came across an explanation on how to properly use the setInterval() function. Essentially, it was mentioned that (function(){ // perform some actions setTimeout(arguments.callee, 60000); })(); ensures that the subsequent call from setTim ...

Having trouble getting the submitHandler method in jQuery validation to work when submitting form data using $.ajax

When I use $.ajax to send data and validate with the jQuery validation plugin, the code looks like this: <div class="" id="ajax-form-msg1"></div> <form id="myform" action="load.php"> <input type="input" name="name" id="name" value ...

methods for retrieving specific key values in javascript

I have an Object containing the following data: const fruits = { apple: 28, orange: 17, pear: 54, }; The goal is to extract and insert the value from the key "apple" into an empty array. While using Object.values.fruits provides all the value ...

Difficulty Encountered in Rendering Component Using setTimeout Function

Having trouble figuring out why my component, enclosed in a setTimeout function, is not appearing on the DOM: const ContentMain = Component({ getInitialState() { return {rendered: false}; }, componentDidMount() { this.setStat ...

Enhance global variable by appending a line from a local function in Javascript

In my js files, I have some global functions that are used in all modules of the application. Currently, I am working on a module that requires modifying one of these global functions to run a local script every time it is called. The issue is that the g ...

Having trouble with jQuery loading for the first time

I am having trouble getting the jQuery to load properly. My goal is to toggle classes on specific items identified by their ID. When an item is clicked, I want it to have the class "menu-selected" while the other item has the class "unselected." I have i ...

The For loop with varying lengths that exclusively produces small numbers

I'm currently using a for loop that iterates a random number of times: for(var i = 0; i<Math.floor(Math.random()*100); i++){ var num = i } This method seems to be skewed towards producing lower numbers. After running it multiple times, the &apo ...

Ways to expedite the process of retrieving data for a JavaScript array

Looking to acquire the creation date of 20000 files and save it in an array. The total time taken is 35 minutes, which seems quite lengthy. (Image Processing Time) Is there a method to generate the array with a quicker processing time? Are there any i ...

Issue with Knockoutjs Custom Binding for Radio Button Groups Failing to Update Selection

I am currently working on creating a unique custom binding in knockout that is similar to the default options binding handler, but instead of a dropdown, it utilizes radio buttons. Whenever an item is added to the array, the update is triggered. However, ...

Learn how to showcase a text file uploaded to a webpage with NODE js and HTML

<!DOCTYPE html> <html> <body> <form action = "/submit" method = "post"> Select a file: <input type="file" name="file"> <input type="submit"> </form> </bod ...

Rotating an object around the camera coordinate using three.js: A step-by-step guide

var newObj = new THREE.CSS3DObject(el); newObj.matrix=camera.matrix.clone(); newObj.matrix.setPosition(new THREE.Vector3(tarX,tarY,tarZ)); //newObj.applyMatrix(new THREE.Matrix4().makeRotationY(rotY)); //newObj.applyMatrix(new THREE.Matrix4().makeRotati ...

What is the best way to swap the values of options between two input select elements?

I am trying to create a feature where I have two select dropdowns with the same options, and when a trigger is clicked, the option values are inverted between the two selects. Here is an example: <select id="source_currency"> <option value="BRL" ...

Learn the process of creating test cases using `ava` for the following code snippet

const TimeToEvent = minutes => { const oneMinute = 1; const minutesInAnHour = 60; if (minutes <= oneMinute) { return "in just 1 minute"; } if (minutes < minutesInOneHour) { return "in mere&quo ...