Retrieving data from the option page's localStorage using the content script

Currently attempting to develop a straightforward chrome extension, however encountering challenges when trying to access the options.html's local storage from my content script "auto.js".

After researching and navigating through Chrome's convoluted documentation, it seems that this can only be achieved using:

chrome.runtime.sendMessage & chrome.runtime.onMessage.addListener

In the content script "auto.js":

var quantity   = ""
var shoe_size  = ""

function addToCart() {

chrome.runtime.sendMessage({localstorage: "qty"}), function(response){
    var quantity = response.qty;
}

chrome.runtime.sendMessage({localstorage: "size"}), function(response){
    var shoe_size = response.size;
}
...

The listener in "options.js":

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse){

  if(request.localstorage == "qty")
    sendResponse({qty: localStorage.qty});
  else if(request.localstorage == "size")
    sendResponse({size: localStorage.size});
  else
    sendResponse({});
});
...

The issue lies in the fact that my quantity & shoe_size variables never receive the values stored in the local storage of the html.

No errors are appearing in my JavaScript console and troubleshooting this problem is proving to be a challenge. Any insights or suggestions would be highly appreciated.

Answer №1

The reason for this behavior is that the codes after sendMessage are executed immediately after it is triggered, without waiting for a response. Although they are set, they may not be available at the exact moment you need them. I encountered a similar issue which was discussed in this post Synchronously get Stored data from content scripts. To address this issue, you can incorporate any desired function within

chrome.runtime.sendMessage({localstorage: "qty"}), function(response){
    var quantity = response.qty;
}

To ensure that the value is set, you can perform the following test:

chrome.runtime.sendMessage({localstorage: "qty"}), function(response){
    var quantity = response.qty;
}

alert("waiting for a second, to make sure that response is ready ...");
alert("Now it is set:" + quantity);

Answer №2

When you write var quantity = response.qty; inside the sendMessage callback function, you are creating a local variable named quantity which coincidentally has the same name as the global variable. However, this local variable exists only within the scope of the sendMessage function and will be cleared from memory once the function finishes execution.

To avoid this, remove the var keyword when declaring quantity inside sendMessage.

Don't forget to add semicolons at the end of your global variables:

var quantity   = "";
var shoe_size  = "";

In addition, consider using console.log in the content script 'auto.js' within the sendMessage callback function. This will allow you to view log messages in the console of the webpage where the script is loaded.

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

Creating a custom filter: How to establish seamless interaction between a script and a node application

I am currently working on implementing a filter feature for a blog using a node express/ MongoDB/Mongoose setup. My goal is to add the 'active' class when a filter is clicked, and then add that filter to an array (filterArray). I want to compare ...

The table from datatables.net is failing to load with Ajax requests

Having trouble with v1.10 Datatables.net table not loading via ajax? The examples and documentation at datatables.net didn't provide a solution. Despite the table displaying, it shows "No data available in table". This issue is occurring in an older M ...

"Within the boundaries of two tags, eliminate any spaces when using the display property set

I'm a bit confused about the behavior of display:inline-block. I noticed that when I use inline-block, it displays content in a smaller space across two tags. However, when I switch to using float: left, everything works fine. Does anyone have an ide ...

Unending React cycles - invoking setState() within a render onClick

Recently delving into React and facing an issue with rendering a button component. My goal is to create a button that, upon being clicked, fetches data and displays it as a list below the button. To achieve this, I am attempting conditional rendering. I ut ...

Should developers avoid using jQuery in ReactJS applications?

While working on a ReactJS project (or any other project), I personally prefer using pure JavaScript over jQuery. Lately, I've started questioning whether it's considered bad practice to use jQuery in ReactJS. Back when I was learning ReactJS, I ...

"Utilizing jQuery to Send POST Requests on Rails - Dealing

Currently, I am running a JavaScript game from file:// and attempting to send a post request to a localhost Rails server in order to add a new high score. In my JavaScript: highScoresEntryView.keyHandlers = function() { var that = this; this.pa ...

Modify the styling of the Checkbox within the script template

I am currently working with a list that contains checkboxes, but they are displaying with the default CSS style. How can I change the CSS style of the checkboxes? Below is the code I am using, and I need to modify the CSS of the checkboxes. <div id ...

What is the best way to delete a jQuery.bind event handler that has been created for an event

I have a div and I need to assign two scroll functions to it, but I also want to remove one of them after a certain condition is met. <div id="div1" class="mydivs"> something </div> <div id="div2">Some crap here</div> <script&g ...

Ways to verify if Arabic text has been submitted by the user through a form?

Is there a foolproof method for detecting Arabic input in a form before submission? Can Javascript effectively manage this task, or is it better handled by server-side scripts like .NET? I propose implementing a script to immediately block users from ente ...

The information being transferred from a jQuery Ajax request to an MVC ApiController Action is disappearing

Let me first mention that although there are similar questions to this one already posted here, I've tried all the solutions and have not had any success. I have an MVC ApiController Action with the following signature: public void Post([FromBody] E ...

In React JSX, what is the best approach for printing a substring?

I am facing an issue with dividing two variables in my React component. I need to display the result to only one decimal place, so I decided to use the substring method like this: <div className="col-md-8"> {(total_star / total_user).toString ...

Dynamically create an array of various objects

I have a task where I need to manage a list of users, each with a checkbox and an input field. My goal is to save all the data when there are changes made to the input field or checkbox: import React, { useState } from "react"; import "./sty ...

What is the best way to organize properties within the Class Variance Authority?

Can the following be achieved in CVA? const mathPanelVariants = cva( 'relative mt-[100px] w-full rounded-sm border-l-[3px] px-[24px] py-[16px]', { variants: { variant: { theorem: { box: 'border-l-[#617bff] dark:bg-[#182 ...

Error message: Authentication timestamp issue with cex.io web socket

Currently in the process of connecting to the CEX.IO bitcoin exchange's websocket. The websocket connection itself is fine, but encountering an error during the authentication phase: "Timestamp is not in 20sec range." Unsure about the cause of this is ...

In search of an explanation for why Promise outcomes for an inline function are not resolving to the desired return value

I have been exploring JavaScript promises and encountered an issue while trying to consolidate promise logic from separate functions into a single inline function. Combining everything into one inline function is causing the return result of the promise to ...

In JavaScript, use regular expressions to replace every instance of a link with its corresponding href object (map link -> a href=link)

I am looking to replace the following text: "wjjghwkjghwkjgh https://www.google.com jhgkwjhgkwhgk https://youtube.com" with: "wjjghwkjghwkjgh <a href='https://www.google.com'>https://www.google.com</a> jhgkwjhgkwhgk <a href=&a ...

DoubleClicking on Checkbox Causes jQuery Click Event to Trigger Twice

Experimenting with DataTables, I have created a table setup like this: <table id='dt'> <thead><!-- Some Header --></thead> <tbody> <tr data-lineid=1> <td><input type=' ...

Implementing a feature to close the drawer component from the main page by clicking on the menu button in React-js

Just starting out with reactjs and I've got my main page set up like this: <div > <AppBar position="flex" style={{backgroundColor:'#1A437E'}}> <Toolbar> <IconButton edge="end" color= ...

best practices for transferring object data to a table with ng-repeat

I have an object called 'SEG-Data with the following structure. I am attempting to display this data in a table using ng-repeat. SEG_Data Object {ImportValues: Array[2]} ImportValues: Array[2] 0: Object ImportArray: "004 ...

The deployment on openshift encountered an error while trying to execute the start script, displaying the message: "ng: command

Upon deploying my app on OpenShift, I encountered the following error within the container: The status of the container is "Crash Loop Back-off." In the local environment, everything works fine with no errors. I double-checked that the Angular package v ...