`store and utilize the data retrieved from chrome.sync.storage.get()`

As I work on a Chrome extension, I am facing an issue with retrieving information from chrome.storage. This involves saving some data in the options page and then accessing it in the content_script.

In the options.js, this is how the information is saved:

function save_options() {
      var color = document.getElementById('color').value;
      chrome.storage.sync.set({
        favoriteColor: color
      }, function() {
        console.log("Color saved");
      });
    }

However, when trying to access this information in my content_script.js, I encountered difficulties. Here's what I attempted:

var color = null;
chrome.storage.sync.get('favoriteColor', function(item){
    color = item.favoriteColor;
});

alert(color); // This line does not work as intended

Answer №1

browser.storage API operates asynchronously, meaning that the code will continue running before the variable color is defined. This often results in receiving an undefined value. To ensure you have the correct value, you must wait for the get method to finish executing. You can achieve this by setting a callback function in your content_script.js file that runs only after the color is fully defined:

    var color = null;
        browser.storage.sync.get('favoriteColor', function(item){
            color = item.favoriteColor;
            alertColor(color);
    });

    function alertColor(color){
        alert(color);
    }

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

Parallel ajax function

After creating a form for registering new accounts, I wanted to ensure that the chosen email is available by checking it against a webservice. However, this process takes a few seconds. Let's take a look at the method used: function validateEmail(ema ...

Safari is capable of rendering Jquery, whereas Chrome seems to have trouble

The code I am using renders perfectly in Safari but not in Chrome. Despite checking the console in Chrome, no errors are showing up. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="ht ...

Error encountered in Ubuntu while attempting to run a Python script within a Node.js/Express application: spawn EACCES

Recently, I set up a node.js server to run a python script using the python-shell . However, after migrating from Windows to Ubuntu, an EACCES error has been persistently popping up. Despite my attempts to adjust permissions and troubleshoot, I haven' ...

The MDX blog was set up to showcase markdown content by simply displaying it without rendering, thanks to the utilization of the MDXProvider from @mdx-js/react within Next JS

I'm currently in the process of setting up a blog using MDX and Next.js, but I've encountered an issue with rendering Markdown content. The blog post seems to only display the markdown content as plain text instead of rendering it properly. If y ...

Passing parameters between various components in a React application

Is it possible to pass a parameter or variable to a different component in React with react-router 3.0.0? For example, if a button is clicked and its onClick function redirects to another component where the variable should be instantly loaded to display a ...

Can you explain the distinction between "javascript:;" and "javascript:" when used in the href attribute?

Can you explain the distinction between using "javascript:;" and just "javascript:" within an anchor tag's href attribute? ...

Leverage Vue's ability to inject content from one component to another is a

I am currently customizing my admin dashboard (Core-UI) to suit my specific needs. Within this customization, I have an "aside" component where I aim to load MonitorAside.vue whenever the page switches to the Monitor section (done using vue-router). Here ...

Adding a div element to a React component with the help of React hooks

I'm currently diving into the world of React and experimenting with creating a todo app to enhance my understanding of React concepts. Here's the scenario I'm trying to implement: The user triggers an event by clicking a button A prompt app ...

The JavaScript function Date().timeIntervalSince1970 allows you to retrieve the time

For my React Native app, I currently set the date like this: new Date().getTime() For my Swift App, I use: Date().timeIntervalSince1970 Is there a JavaScript equivalent to Date().timeIntervalSince1970, or vice versa (as the data is stored in Firebase clo ...

Is it possible to execute a URL twice instead of just once in AngularJS?

While developing a web application with AngularJS and Rest Web services, I encountered a problem where the URL is being executed twice instead of just once. I have created a service function for executing the web service API and calling it from the control ...

Saving JSON data into an HTML element using Handlebars templating

Is there a way to save the entire JSON object within an HTML element as a data attribute? let a = {name : "sample", age : "34"} $.find('#someDiv').data('adata', a); Is it possible to achieve the same result using Handlebars when creat ...

jQuery load() issue

$('form.comment_form').submit(function(e) { e.preventDefault(); var $form = $(this); $.ajax({ url : 'inc/process-form.php', type: 'POST', cache: true, data:({ comment ...

How to access a controller function within a recursive directive template in Angular version 1.3?

In my parent directive, I am able to access controller functions using the $parent operator. However, this method does not work in recursive child directives. Here is a shortened example of the issue: // Sample controller code (using controllerAs):--- va ...

When the response is manually terminated, the next middleware layer in express.js is invoked

I recently noticed an unusual occurrence: Even though I am explicitly ending the request using res.json() in one express middleware, the request still cascades down to the next middleware. It is important to mention that I am not utilizing next() anywhere ...

JavaScript - memory heap exhausted

Recently, I encountered an issue with my API written in Node.js. The purpose of this API is to read data from a MySQL database, write it into a CSV file, and allow users to download the file once the writing process is complete. Initially, everything was f ...

What is preventing me from using AJAX to input data into sqlite?

Implementing a local save feature in my Web App is proving to be quite challenging. Every time I attempt to send data in any form, I consistently encounter the following error: A builtins.TypeError occurs, followed by a stack trace in /SaveFile and jquery ...

Adjust the size of the Threejs canvas to fit the container dimensions

Is there a way to determine the canvas size based on its container in order to prevent scrolling? Setting the size based on the window results in the canvas being too large. ...

What is the process for performing the "extract function" refactoring in JavaScript?

Are there any tools for extracting functions in JavaScript similar to the "extract function" refactoring feature available for Java and jQuery developers in Eclipse or Aptana? Or perhaps in another JavaScript/jQuery IDE? ...

Embed JavaScript locally within an iframe HTML

When attempting to add HTML code within an iframe to showcase data, everything works as expected. However, the issue arises when trying to include any JavaScript within the iframe, as it doesn't seem to be recognized locally. Below is the example cod ...

Unable to transfer information from the Parent component to the Child component

Can you help me solve this strange issue? I am experiencing a problem where I am passing data from a parent component to a child component using a service method that returns data as Observable<DemoModel>. The issue is that when the child component ...