Unable to save data in local storage

I'm enhancing an existing chrome extension while ensuring a consistent style. I am looking to implement a new feature, and I have written a script that saves the user's selection from the popup and sets a new popup based on that choice going forward.

userchoices.js:

require.scopes["userchoices"] = (function() {

var exports = {};

var userChoices = exports.userChoices = {
  userchoices: {},
  updateChoice: function(){
    self = this;
    chrome.storage.local.get('userchoices', function(items){
      if(!items.userchoices){
        chrome.storage.local.set({userchoices: self.userchoices});
        return;
      }
      self.userchoices = items.userchoices;
    });
  },
  getChoice: function(url){
    if(this.userchoices[url]){
      return this.userchoices[url][choice];
    } else {
      return {};
    }
  },
  setChoice: function(url, newChoice){
    if(!this.userchoices[url]){
      this.userchoices[url] = {};
    }
    this.userchoices[url][choice] = newChoice;
    chrome.storage.local.set({userchoices: this.userchoices});
  },
  removeChoice: function(url){
    if(!this.userchoices[url]){
      return;
    } else {
      delete this.userchoices[url]
    }
    chrome.storage.local.set({userchoices: this.userchoices});
  }
}
return exports; 
})(); 

background.js:

var userChoices= require("userchoices").userChoices;

chrome.windows.onCreated.addListener(function(){
  CookieBlockList.updateDomains();
  BlockedDomainList.updateDomains();
  FakeCookieStore.updateCookies();
  userChoices.updateChoice();
});

function refreshIconAndContextMenu(tab)
{
  // The tab could have been closed by the time this function is called
  if(!tab)
    return;
  var choice = userChoices.getChoice(tab.url);
  if(choice) {
    if (choice == "one"){
        chrome.browserAction.setPopup({tabId: tab.id, popup: "skin/popupDontCare.html"});
    } else if(choice=="two"){
        chrome.browserAction.setPopup({tabId: tab.id, popup: "skin/popupSortofCare.html"});
    } else if(choice=="three") {
        chrome.browserAction.setPopup({tabId: tab.id, popup: "skin/popupCare.html"});
    } else if(choice=="four") {
        chrome.browserAction.setPopup({tabId: tab.id, popup: "skin/popupReallyCare.html"});
    } else {
        chrome.browserAction.setPopup({tabId: tab.id, popup: "skin/popup.html"});
    }}
}
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
  if(changeInfo.status == "loading")
    refreshIconAndContextMenu(tab);
});

// Update icon if a tab is replaced or loaded from cache
chrome.tabs.onReplaced.addListener(function(addedTabId, removedTabId){
  chrome.tabs.get(addedTabId, function(tab){
    refreshIconAndContextMenu(tab);
  });
});

popup.js:

var userChoices = require("userchoices").userChoices;
function init()
{
  console.log("Initializing popup.js");
  // Attach event listeners
  $("#Dont_Care_btn").click(doNothing);
  $("#Sort_of_Care_btn").click(doBadger);
  $("#Care_btn").click(giveSecrecyBadger);
  $("#Really_Care_btn").click(giveAdvice);
  $("#Nuance_btn").click(addNuance);
}

function doNothing() {
  $("#startingQuestion").hide();
  $("#DontCareResponse").show();
  $("#siteControls").hide();
  userChoices.setChoice(tab.url, "one");
  refreshIconAndContextMenu(tab);
 }

function doBadger() {
  $("#startingQuestion").hide();
  $("#SortofCareResponse").show();
  $("#siteControls").hide();
  $("#blockedResourcesContainer").hide();
  $("#Nuance_btn").show();
  userChoices.setChoice(tab.url, "two");
  refreshIconAndContextMenu(tab);
 }

function giveSecrecyBadger() {
  $("#startingQuestion").hide();
  $("#siteControls").hide();
  $("#CareResponse").show();
  $("#siteControls").hide();
  $("#blockedResourcesContainer").hide();
  $("#Nuance_btn").show();
  userChoices.setChoice(tab.url, "three");
  refreshIconAndContextMenu(tab);
}

function giveAdvice() {
    $("#startingQuestion").hide();
    $("#siteControls").hide();
    $("#ReallyCareResponse").show();
    userChoices.setChoice(tab.url, "four");
    refreshIconAndContextMenu(tab);
}

The current issue is that the popup is not being set, and it's unclear whether the selection is being saved successfully. Is there any problem you can see?

Answer №1

Wow, while attempting to simplify the issue, I stumbled upon the solution! It turns out that the outdated chrome.tabs.getSelected method was causing the problem, when in fact it should have been chrome.tabs.query()

Big shoutout to Xan for the help!

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

The error in ReactJS is coming from the render method of the `News` component

While working with React JS, I encountered an error when trying to run a particular code snippet. The error message displayed was: "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got ...

Unable to transfer AJAX data to PHP script

Trying to figure out how to send AJAX data to PHP. While I am comfortable with PHP, JavaScript is a bit new to me. Incorporating HTML / JavaScript <input type="text" id="commodity_code"><button id="button"> = </button> <script id="s ...

Completely different method for transmitting an array to NodeJS through AJAX

Recently, I've encountered difficulties when sending arrays to NodeJS using AJAX. It seems that whenever I try to send it with JSON, the error function is always triggered. Despite seeking explanations, I haven't found a satisfactory answer. The ...

Every single checked value in the checkbox variable

Encountered a small hiccup. Let me explain. In my form, there are 8 checkboxes. The goal is to loop through and capture the value of each checked checkbox using a variable. However, I'm always getting the same value from the first checkbox. Here&apo ...

Why does the for loop assign the last iteration of jQuery onclick to all elements?

I've encountered an issue with my code that I'd like to discuss var btns = $('.gotobtn'); $('#'+btns.get(0).id).click(function() { document.querySelector('#navigator').pushPage('directions.html', myInf ...

What is the best way to read a file or Stream synchronously in node.js?

Kindly refrain from lecturing me on asynchronous methods. Sometimes, I prefer to do things the straightforward way so I can swiftly move on to other tasks. Unfortunately, the code below is not functioning as expected. It closely resembles code that was po ...

Insert, delete, and modify rows within the table

I'm struggling with a JavaScript issue and could use some help. How can I add a new row for all columns with the same properties as the old rows, including a "remove" button for the new row? Is there a way to prevent editing cells that contain b ...

Creating a function for loading dynamic content in XSLT can be achieved by following these steps

When I call the function collapseandexpand() for static elements only, it does not work. Now, how can I create the same function to handle dynamic content in xslt? Javascript Code: <script language="javascript" type="text/javascript> <xsl:text&g ...

How to ensure the table fits perfectly on the screen using JQueryMobile and Cordova?

I've been working on a JavaScript function that creates a dynamic page and displays data fetched from a database. However, I've encountered an issue where the displayed data overflows past the width of the mobile screen. Is there a way to ensure ...

What is the process for managing items in an array within a separate file?

I am facing an issue where I need to display the 'title' object from an array in the document App.js. Everything works fine when I use an array without any objects: (before) App.js: import React from 'react' import TodoList from ' ...

Is it possible for me to identify the original state of a checkbox when the page first loaded, or the value it was reset to when `reset()` was

When a webpage is loaded, various input elements can be initialized as they are declared in the HTML. If the user modifies some of the input values and then resets the form using reset(), the form goes back to its initially loaded state. I'm curious, ...

Sending an XMLHttpRequest in PHP causes a blank array to be returned

> xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var jsondata = xmlhttp.responseText; console.log(xmlhttp.responseText); document.getElementById("jsondata").value = js ...

The significance of API Input Validation and Steering Clear of Lengthy Conditional Statements

Currently, I am working on ensuring that my API functions correctly even in cases of bad or missing data. At the moment, I have an if statement that checks for any missing inputs. If an input is missing, it returns false, otherwise there is a large else b ...

A React-based frontend solution designed exclusively for managing data structures and databases

Challenges with Product Management In my React App, the shop features products sourced solely from a JSON file as an external API, all managed on the frontend. Recently, I encountered a product with limited availability - only 20 pieces in stock. I am uns ...

Guarantee the successful execution of a server-side function using my client-side function

I am currently in the process of creating a website that utilizes Javascript and Asp.net. My code contains numerous functions on the client side, within my html code, while my server side functions are called using a webservice. How can I ensure that my c ...

Performing multiple AJAX calls from JavaScript

for(var y=0 ; y<=23 ; y++) { AjaxRequest99 = null; AjaxRequest99 = getXmlHttpRequestObject(); // method to initiate the request if(AjaxRequest99.readyState == 4 || AjaxRequest99.readyState == 0) { AjaxRequest99.open("GET", "aja ...

The random number generator in TypeScript not functioning as expected

I have a simple question that I can't seem to find the answer to because I struggle with math. I have a formula for generating a random number. numRandomed: any; constructor(public navCtrl: NavController, public navParams: NavParams) { } p ...

Measuring the height of a div element using Vuejs

Let me explain my current situation: I am trying to determine the height of a DIV component in order to dynamically inform its child component about its size. I have been working on implementing manual loading mode, but I have encountered an issue where t ...

Exploring a JavaScript object to verify if a property contains nested data elements

I am currently working on traversing through the object above in order to determine if a contact is a member of a specific list. For instance, if the user is a member of the list with an ID of 2022, I want to display their first name (which is also includ ...

Is there a way to incorporate a computed value into a table prop while working with Element UI?

In my frontend development, I am utilizing vuejs along with element ui. I am faced with the task of rendering a table that includes dates in unix format. To make these dates more user-friendly, I have incorporated moment.js to convert them into a readable ...