alexmorgan.cr
alexmorgan.cr

Reputation: 300

Continue saving Local Storage even if user refresh pages

I have an application that performs an ajax request to retrieve some data y need to know if is there a background process to continue saving the request in local storage even if the user exits the page.

I did find solutions to avoid the user exit the page with a "onbeforeunload" event but this is not a solution.

//Clean local storage on begin the load localStorage.removeItem('prizes');

var request = $.post(url, {test:test})
                .success( function(data){

                  localStorage.setItem('prizes', JSON.stringify(data));

                },4000)

//Get local storage

$('body').on('click','#remove',function(e){
    e.preventDefault(); 
    //fake data
    localStorage.removeItem('prizes');

});

$('body').on('click','#show',function(e){
    //fake data
    e.preventDefault(); 
    //fake data
    var data = localStorage.getItem('prizes');
    console.log(data)
});

//Force the user to not refresh the page with an alert message
window.onbeforeunload = function(){
  if(!request){
    return "Request not finished";
  }
}

The idea is when the ajax gets triggered perform to save the data in local storage even if the user exits the page.

Upvotes: 0

Views: 169

Answers (1)

Abishek H
Abishek H

Reputation: 209

 window.addEventListener('storage', (e) => {
  if (e.key === 'prizes') {
    data = JSON.parse(e.newValue)
    console.log(data)
  }
})

Hope this works.

Upvotes: 1

Related Questions