Skip to content Skip to sidebar Skip to footer

How To Store A Variable In Local Storage?

I am running a script and I am using a meta refresh as it could stop due to internet connection or server downtimes or anything: The

Solution 1:

Assuming localStorage is available and I understood your issue:

// first declare a variable but don't assign a valuevar myId;
// then check whether your localStorage item already exists ...if (localStorage.getItem('titles')) {
    // if so, increase the value and assign it to your variable
    myId = parseInt(localStorage.getItem('titles')) + 1;
    // and reset the localStorage item with the new valuelocalStorage.setItem('titles', myId);
} else {
    // if localStorage item does not exist yet initialize// it with your strat valuelocalStorage.setItem('titles', 1);
    // and assign start value to your variable
    myId = paresInt(localStorage.getItem('titles'));
}
console.log(myId);

Now each time the page loads the code checks whether there is a localStorage item "titles".

If so, the value of "titles" is increased by 1 and the resulting value is assigned to "myId".

If the localStorage item is not there yet it's initialized with the start value and the start value is assigned to "myId" as well.

Note that localStorage keys and values are always strings and that an integer value is always converted to a string.

Solution 2:

First check if your browser supports local storage like this (local storage will persist across page refreshes unlike sessionStorage)

if (typeof(Storage) !== "undefined") {
    // Code for localStorage/sessionStorage.// Store valuelocalStorage.setItem("keyName", variable);
   // Retrieve value from local storage and assign to variablevar myId = localStorage.getItem("keyName");
} else {
    // Sorry! No Web Storage support..
}

Post a Comment for "How To Store A Variable In Local Storage?"