Ways to determine if a key is configured in chrome.storage?

Currently working on a Google Chrome extension and I need to verify if a key is present in chrome.storage.sync.

For instance:
I am aiming to confirm the existence of the key 'links':

if (chrome.storage.sync.get('links', function() {
    // If already exists, no action needed 
}));
else{
    // If not found, set it 
}

Would appreciate any useful suggestions.

Answer №1

Initially, due to the asynchronous nature of chrome.storage, all operations must be carried out within the callback function. It is not possible to use an if...else statement outside of the callback since no data will be returned at that point. Chrome responds to queries by passing a key-value dictionary to the callback, even when only requesting one key.

Therefore,

chrome.storage.sync.get('links', function(data) {
  if (/* condition */) {
    // do nothing if already set
  } else {
    // set the value if not already set
  }
  // You can determine which branch was executed here
});
// It is unknown at this point which branch will be executed - it has not occurred yet

There is no distinction between the value undefined and being absent in storage. To account for this, you can check as follows:

chrome.storage.sync.get('links', function(data) {
  if (typeof data.links === 'undefined') {
    // do nothing if already set
  } else {
    // set the value if not already set
  }
});

On another note, chrome.storage offers a more convenient pattern for handling such scenarios. By specifying a default value in the get() method:

var defaultValue = "Default if unset";
chrome.storage.sync.get({links: defaultValue}, function(data) {
  // data.links will contain either the stored value or the default if not set
  chrome.storage.sync.set({links: data.links}, function() {
    // The value is now stored, eliminating the need for repetition
  });
});

It is recommended to establish defaults during startup; events like chrome.runtime.onStartup and/or chrome.runtime.onInstalled in a background/event page are suitable for this purpose.

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

Terminate a remotely shared ngrok session that is forwarding a React application

My coworkers and I share an ngrok account while developing a React application using 'npx create-react-app' on UNIX-like systems. Occasionally, when trying to spin up an HTTP tunnel, I encounter the message: Your account '*****@*********.com ...

Transform HTML components into visual representations (on the server)

I am looking for a way to convert dynamic HTML elements into image files such as jpg or png. I do not want to capture a screenshot of a webpage or a static HTML file. My goal is to achieve something similar to the following, but executed on the server-sid ...

Switch to display only when selected

When I click on the details link, it will show all information. However, what I actually want is for it to toggle only the specific detail that I clicked on. Check out this example fiddle Here is the JavaScript code: $('.listt ul').hide(); $( ...

Calculate the cumulative values in ng-repeat using AngularJS

I used ng-repeat to iterate through a JSON array. I calculated the number of nights by utilizing the dayDiff() function. Now, I need to find the total number of nights for all invoices. My project is built with AngularJS. Is there a way to retrieve the to ...

I encountered an error stating "Module Not Found" while attempting to locate slick-carousel/slick/slick.css. This issue arose while implementing reacy-slick within my Next.js project

While working on my app with Next.js, I wanted to incorporate a carousel like Slick to display images. I followed the official documentation carefully, imported the necessary CSS file, but encountered an error stating "Module Not Found, can't resolve ...

Refreshing the webpage with new data using jQuery after an AJAX request is

I'm experiencing a problem where the DOM is not updating until after the completion of the $.each loop. On my website, I have several div elements that are supposed to turn orange as they are being looped over. However, once the data is sent to the s ...

There is no need for updates as git is already current for some mysterious reason

As a newcomer to git, I've been trying to wrap my head around it but still struggling. Can someone help clarify this for me? My question pertains to the 'master' branch in git which contains the following code: const list = [ 'h&ap ...

Populating HTML input field with AJAX response

One challenge I am facing involves a dropdown menu containing Course Titles sourced from a database in the index.php file. After capturing the selected data from the dropdown, I transmit it to a PHP file. In this PHP file, using the received Course Title, ...

Verify the status of the mongodb server synchronously

Is there a method to detect if a mongod instance is still operational while using mongoclient? In my mongoclient module, I have implemented a db.on('close') handler which functions properly when mongod exits normally. However, if the server proc ...

Troubleshooting React Native in VS Code using Node shims

I recently started working on a React Native project using the Ignite CLI 2.0.0 default boilerplate, and I find myself in need of some dependencies from node-based packages. To address this, I created files named transformers.js, babel-transform.js, and r ...

Sending JavaScript Variables to MySQL Database via PHP

I'm currently attempting to pass a JavaScript variable to PHP, but I'm unsure of the best method to do this. I've heard about Ajax, but I haven't used it before and find it difficult to understand. Can anyone suggest an easier way to ac ...

Changing the direction of scrolling in AngularJS

I'm currently working on an Ionic / Angular application and I've come across a situation where I need to change the scroll direction when scrolling. Usually, when you scroll down, the content moves down as well. However, I want to achieve the opp ...

Implementing a dynamic like functionality using Ajax in Django

I've created a new structure for the like button, but it's not functioning correctly. Here are the files I'm working with: models.py class Comment(models.Model): title = models.CharField(max_length=50) author = models.ForeignKey(Pr ...

Caution: An invalid next.config.js file has been detected while running the Next.js project

Whenever I try to run my project, I encounter the following three warnings: 1- warn - We found some invalid options in your next.config.js file. The property webpack5 is not recognized and may cause issues (allowed properties are: amp, analyticsId, assetP ...

Having trouble modifying the fields in the formArray

https://i.sstatic.net/B4uTq.pngWorking with reactive forms, I have a UI feature that displays radioButton options which, when selected, reveals details about the chosen value within the form. Once a button is selected, the form fetches data from the backen ...

Utilizing APIs to track YouTube subscriber data

I want to set up a page with just one YouTube subscribe button. When a user clicks on the button, a subscription request will be sent to the YouTube channel specified in the code, and the user will be subscribed. If the user is not logged in to Gmail, the ...

Solving the Issue of Handling Custom Events in Javascript

I've been experimenting with a simple CodePen that features a basic table with three rows. I'm trying to attach event handlers to each row in the table and trigger the event by pressing a button. However, I'm facing an issue where the attac ...

JavaScript lacks the power to persuade the mouse into altering its cursor

I am encountering an issue with my ASP.NET page that contains an Infragistics webgrid. I have implemented Javascript methods to handle the mouseover and mouseout events on the grid rows, changing the mouse cursor to a pointer and back to the default as use ...

What is the best way to remove every other second and third element from an array?

I am looking to remove every second and third element of an array in Javascript. The array I am working with is as follows: var fruits = ["Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10"]; My goal is to delete every second and ...

Exclude certain packages from being processed in webpack

After setting up my webpack configuration, everything was running smoothly with the specified packages in the package.json: { "peerDependencies": { "react": "16.13.1", "react-dom": "16.13.1", ...