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 dollar sign function operates properly, but encountering issues with the $.ajax function (non-slim)

I'm facing some issues with my jQuery code. I have included jQuery (not slim) and for some reason, $.ajax is failing. However, '$' and 'jQuery' functions are working fine. It seems like a simple problem but I can't seem to fi ...

Having trouble retrieving data from a JSON object that has been stringified. This issue is arising in my project that utilizes Quasar

I successfully converted an excel spreadsheet into a JSON object by using the xml2js parseString() method, followed by JSON.stringify to format the result. After reviewing the data in the console, it appears that I should be able to easily iterate through ...

How to properly stop a sequence of notes using WebAudio in an asynchronous manner?

Utilizing WebAudio for playing a sequence of musical notes has been quite successful. I have a playNote function that takes note frequency, start times, and stop times for each note as input. The parameters for generating the sequence are set prior to the ...

Mastering the Vue 3 Composition API: A guide to efficiently utilizing it across multiple Vue instances spread across different files

tl;dr What is the best way to import Vue3 in a base Javascript file and then utilize Vue's composition API in subsequent standalone files that will be loaded after the base file? I incorporate Vue to improve user interactions on specific pages like t ...

Is there a way to dynamically update text using javascript on a daily basis?

I am currently developing a script to showcase different content and images every day. While I have successfully implemented the image loop to display a new picture daily, I need assistance in achieving the same functionality for the title. My aim is to c ...

Experimenting with TypeScript code using namespaces through jest (ts-jest) testing framework

Whenever I attempt to test TypeScript code: namespace MainNamespace { export class MainClass { public sum(a: number, b: number) : number { return a + b; } } } The test scenario is as follows: describe("main test", () ...

Responsive Fullscreen Bootstrap Panel with Highcharts

One issue I'm facing is with my (bootstrap) panels that contain Highcharts charts and I want them to show fullscreen without losing their aspect ratio. The problem is that the size of the Highcharts does not adjust when going into full-screen mode. Is ...

When the Ajax "GET" request is made to the intra-service, the CMS service worker will respond with an "OK" even when offline

Hello there, We are currently utilizing an open-source CMS that recently received an upgrade with a new feature - a javascript serviceworker implementation to manage all requests. This CMS includes workflow forms where users engage (created by us). Durin ...

I am unable to retrieve the values from a manually created JavaScript list using querySelectorAll()

const myList = document.createElement("div"); myList.setAttribute('id', 'name'); const list1 = document.createElement("ul"); const item1 = document.createElement("li"); let value1 = document.createTe ...

Generating an HTML table with JSON data in JavaScript

I'm still struggling with JavaScript as a beginner, so please bear with me and provide guidance step by step. Also, try to avoid overwhelming the comments with links as it confuses me. This is an attempt to bypass the CORS issue. <!D ...

Execute the controller function once all asynchronous calls to the Angular service have finished

I have integrated the Angular Bootstrap Calendar using a custom cell template and cell modifier. Within my controller, I need to retrieve configuration data from a service that is required by the cellModifier function before it is executed. (function() { ...

What is the best method to retrieve child elements from a class list object?

Seems like I have a similar content class <div class="parentclass"> <div class="childClass"> </div> <div class="childClass"> </div> <div class="childClass"> </d ...

Using HTML, CSS, and JavaScript, the main tab must include nested subtabs to enhance navigation and

When a user clicks on a tab, another tab should open within the main tab. Depending on the selection in the second tab, input fields should appear while others hide. Something similar to the nested tabs on expedia.com. I have experimented with the tab vie ...

Implementing event handling with .On() in Jquery following .Off()

I need assistance with my responsive navigation bar. I am having trouble with the jQuery code to disable hover events if the width is less than or equal to 768px and enable it for desktop screens. $(window).on('load resize', function (e) { v ...

dispatch email display Twitter Bootstrap notification utilizing Ajax

I'm trying to set up an email sending feature via a contact form. I want it to send the email and display a Bootstrap alert confirming that the email has been sent. Below is the HTML code: https://jsfiddle.net/6rfeas35/. Additionally, here is my PHP c ...

Is it possible to customize the MongoDB Collection before loading the web application by fetching data asynchronously using Promises?

I am currently working with MongoDB and NodeJS, trying to preload my Collection customers every time the site is loaded. The process involves emptying the collection, populating it with empty Documents, and then replacing them with real data fetched from a ...

Conditionally defining variables in JavaScript only if they are currently undefined

I have been working on extracting two keywords from a URL in the following format: localhost:3000/"charactername"/"realmname" My goal is to extract "charactername" and "realmname" and assign them to variables. Here is the code snippet I am using: var c ...

There was an issue encountered while trying to install Electron using the command 'npm install electron'

While attempting to install electron using npm install electron, I encountered the following error: 908 error code 1 909 error path C:\Users\name\Documents\name\Code\code\node_modules\gl 910 error command failed ... ...

Arrays in Javascript (correlating)

I'm having trouble figuring out what needs to be included in this code (I apologize that it's in German, it's an array corresponding to images for JavaScript.) function namenZuBildern(){ var bilder = new Array( "000227", "000228", " ...

How to send two different types of data using jQuery/AJAX to a .php file? (Syntax)

I am completely new to the world of jQuery/AJAX and I could really use some guidance. Here is the code snippet in question: $(function () { $('.button').on('click', function (event) { event.preventDefault(); //prevents ...