What is preventing me from viewing the recent values I clicked on in my local storage?

Working on a google chrome extension, I am facing challenges in utilizing local storage to retain the value of the last clicked button. My goal is to ensure that the last clicked button remains visible even after closing the popup. Despite my efforts with local storage, the button fails to persist once the popup is closed. Checking the application's local storage while inspecting reveals that the last clicked values are not being saved.

This https://i.sstatic.net/rjgB8.png and this https://i.sstatic.net/KFJG6.png show some screenshots of the issue at hand. It seems like I might be approaching this problem incorrectly. Would anyone happen to know what might be causing this discrepancy?

//Button identifiers for starting and stopping logging
const btnStart = document.getElementById("click-start");
const btnStop = document.getElementById("click-stop");


var lastClicked = document.getElementById("btnStartID");

//Logic for controlling start/stop buttons
document.addEventListener("DOMContentLoaded", function () {
    
    //Retrieve lastClicked to make decisions
    chrome.storage.local.get(['lastClicked'], function(result) {
        
        if (result == document.getElementById("btnStartID")) {
            //Works as expected
            btnStart.style.display= "none";
            btnStop.style.display= "block";
             console.log("last clicked is start button");
            Logger(true);
        } else if (result == document.getElementById("btnStopID")) {
            //Not functioning correctly
            btnStart.style.display= "block";
            btnStop.style.display= "none";  
            Logger(false);
            console.log("last clicked is stop button");
        } else {
            //Verify if the IDs of elements are being grabbed properly
            console.log("else statement");
            Logger(true);
        }
        
        //Adding functionality to Start button   
        btnStart.addEventListener("click", function() {
            lastClicked = document.getElementById("btnStartID"); 
            Logger(true);
            chrome.storage.local.set({'lastClicked': lastClicked}, function() {
                console.log('logging started successful');
        }); 
        });
     
        //Adding functionality to Stop button
        btnStop.addEventListener("click", function() {
            lastClicked = document.getElementById("btnStopID"); 
            Logger(false);
            chrome.storage.local.set({'lastClicked': lastClicked}, function() {
                console.log('logging stopped successful');
        });
        });
    
    });
    
});

chrome.storage.local.get(['key'], function(result) {
    console.log('value currently is ' + result.key);
});


//Process to enable Start/Stop logging buttons--work in progress
function Logger(isLogging) {
    
        let logger =''
        if (isLogging){
        
        btnStart.style.display= "none";
        btnStop.style.display= "block";
        logger = 'logging' 
        addRow();
    } else {
        
        btnStart.style.display= "block";
        btnStop.style.display= "none";

        logger = 'not logging'
    }
    
    //Utilizing storage API to save data for the last pressed button--work in progress
    chrome.storage.local.set({key: logger}, function() {
        console.log('value is set to  ' + logger);
    }); 
}    

Answer №1

Storing data in local storage is limited to strings, causing Chrome to disregard your effort to save an entire button. To overcome this limitation, consider saving the button's id instead:

if (result.lastClicked == "btnStartID") {
  ...
chrome.storage.local.set({'lastClicked': lastClicked.id}

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

Guide on using Ajax to log a user in post-registration in Laravel 5.4

I am currently working on implementing a Modal registration box using Ajax. Everything is functioning properly, but I am facing an issue with logging the user in as well. Below is the modified register function in RegisterController.php: /** * Managing ...

When it comes to the CSS `:visited` pseudo-class, I have

I'm having trouble changing the color of the anchor tag and blurring the image after visiting the link. Despite my CSS code, only the color is changing and the image remains unchanged. Here's my CSS code: <style> .image123{ paddin ...

Struggling to pass command line arguments to index.ts with yarn?

My objective is to pass arguments through the command line using yarn start to index.ts. "scripts": { "start": "tsc-watch --onSuccess \"ts-node --pretty -r tsconfig-paths/register' src/index.ts\"", } When I attempt something like: yarn ...

When attempting to import a store in the routes.js file while running Jest tests in Vue.js, an error

My current setup involves using vue-test-utils along with jest for Test-Driven Development (TDD). In the route file (routes.js) of my Vue.js application, I have imported the $store object and utilized it for various functionalities. While writing a basic u ...

Using Angular JS to conceal a div within an ng-repeat loop

Looking for a way to hide a progress bar within an ng-repeat loop? You may be thinking about utilizing ng-hide, but running into issues with multiple iterations and divs sharing the same ID. The goal is to display the div when a user clicks on a button. A ...

Function not being called by JQuery selector

Having an issue with a specific Jquery selector. $("#confirmEmailInput").change(function() { validate() confirmEmail() }); The current selector I'm using is shown above. My goal is to have the functions called upon a change in ...

Unexpected Error: The axiosCookieJarSupport function is throwing a TypeError, functioning properly in Node.JS but not in .vue pages. What could

Struggling with a function that authenticates on a website, it runs smoothly in a basic node.js script but fails when executed from a .vue page within the NuxtJS framework. The error message received when running in the .vue page is TypeError: axiosCookie ...

Leveraging javascript for substituting on-page javascript functionality

Dear fellow coders, I am still learning the ropes of Javascript, so please bear with me. I’ve encountered this snippet on a webpage: <script type="text/javascript"> bb1 = "oldcode"; bb2 = "morecodehgere"; bb3 = 160000;</script> My goal is ...

Deleting an element from an array in JavaScript by its index

I'm currently working on a todo type app and I need to figure out how to remove an array element. Adding elements using element.push() is straightforward, but removing them is a bit more challenging. The remove button is nested within a template liter ...

What is the method to extract the Text from a Radio Button List?

<asp:RadioButtonList ID="rbl" runat="server" onMouseUp="Myf()"> <asp:ListItem Text="Yes" Value="1"></asp:ListItem> <asp:ListItem Text="No" Value="0"></asp:ListItem> </asp:RadioButtonList> function My ...

A comprehensive guide on creating translation files using grunt angular-translate from original JSON files containing translations

I have a unique angular application that requires support for multiple languages. To achieve this, I have implemented the angular translate task in the following manner. My goal is to create separate language files which can be loaded later using the useSt ...

Entering a new row and sending information through ajax

I'm looking for some help with a web page I have that includes a particular table structure: **Check out my Table*:* <table id="staff" class="table"> <thead> <tr> <th>First Name</th> <th>Last Nam ...

Extract the range of dates for the current month from a JSON response using jQuery

I am currently working on an application and have received a response from the AJAX request that looks like this: { "country": "italy", "timeline": { "cases": { // dates of cases in Italy }, "deaths": { // dates of deaths in It ...

Extracting information from a complicated and unreliable JSON structure

Dealing with a JSON object retrieved via POST query, I am facing the challenge of setting variables due to the varying order of results. This inconsistency is causing issues with my variable assignment based on array positions: var idle = Example1.results[ ...

Struggling to delete elements from observable array within Knockoutjs framework

I am attempting to use knockoutjs to remove a user from an observable array called users. It seems like my viewModel may not be working correctly because it is within a document.ready function. Here is some context about the code below: My application fet ...

Check if there are any child nodes before executing the RemoveChild JavaScript function to avoid any errors

function delete(){ let k = document.getElementsByClassName('row'); for(let i=0; i<k.length; i++) { if(k[i].hasChildNodes()){ k[i].removeChild(k[i].childNodes[2]); } } } <div id="table"> <div class="row"& ...

"Ng-repeat function seems to be malfunctioning, although I am able to view

There seems to be an issue with ng-repeat when dealing with an array of objects: dummy.json [ {"name":"alpha", "data":[{"name":"Unit 1", "prereqs":[]}]}, {"name":"beta", "data":[{"name":"Unit 1", "prereqs":[]}]} ] While I am able to fetch the total ...

Can you iterate through two arrays to find common values?

Upon examining my firebase database, I found the following structure: Users { askdfasdf: John: { Selection: [1,2,3] }, fasfadffe: Mark: { Selection: [1,2,4] } } Players { { name: &apos ...

After changing the value of a <select> element in Vue, the fetched data is delayed by one step

I'm currently working on a feature that involves fetching data from a URL that changes every time a user chooses a new value from a <select> dropdown. The fetched data updates the songkickData array with the latest information. However, when I c ...

Utilize an AJAX call to fetch an array and incorporate it within your JavaScript code

Currently, I am in the process of building a live update chart feature. To access the necessary data, I created a separate file which contains the required information. Through AJAX, I sent a request from my main page to retrieve an Array and incorporate i ...