即使用户刷新页面也继续保存本地存储

时间:2019-05-22 13:57:10

标签: javascript jquery cookies local-storage

我有一个执行ajax请求以检索某些数据的应用程序,您需要知道是否存在后台进程来继续将请求保存在本地存储中,即使用户退出页面也是如此。

我确实找到了避免用户使用“ onbeforeunload”事件退出页面的解决方案,但这不是解决方案。

//在开始加载时清除本地存储     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";
  }
}

这个想法是当ajax被触发时,即使用户退出页面,也要执行将数据保存在本地存储中的操作。

1 个答案:

答案 0 :(得分:0)

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

希望这行得通。

相关问题