简体   繁体   中英

Init localStorage after every refresh

I would like to initialize localStorage object every time a user does a refresh by F-5.

Can i do such a thing?

The localStorage object is working fine by setItem and getItem methods. However, I would like to know if i have the option to init this object every refresh action.

For example: I have two different pages in my app. A.js and B.js. When loading B.js i set the localStorage:

var id = getId();
window.localStorage.setItem("Id", id );

After that when i clicking on a button for going to A.js i am doing:

var selectedId = window.localStorage.getItem("Id");

if (selectedId !== null){
    var intSelectedId = parseInt(selectedId );
   //DO LOGIC
 }

I would like to delete ("Id", id) key-value pair every refresh. How can i do it?

Maybe like this ?

//declare in global scope
var myinitvalue = "blah";
//handle what happens just before page unloads
window.onbeforeunload = function() {
    window.localStorage.setItem("Id", myinitvalue);
}

Unfortunately the side effect of this is that the value will also reset if browser tab is closed or if back button is clicked.

If you want to delete item with key Id once your page is loaded, do

window.onload=function(){
   localStorage.removeItem("Id");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM