How to clear sessionStorage when navigating to another page but not on refresh?

家住魔仙堡 提交于 2021-01-27 08:10:15

问题


I have some check boxes in one of my webpages, and this page has to refresh every 1 minute for some data consistency issues.

I am using window.sessionStoage to persist the check boxes that have been checked so that the user doesn't lose the boxes already checked on page refresh.

But I want to clear the sessionStorage when the user navigates away from that page (not necessarily leaving my website, might be going to another page on the same website), and for the same if I use the onunload event then the storage will be cleared in case of refresh also.

Is there any other event or any workaround that could help me achieve this.


回答1:


May you try to save the path/name of the current page in you session-storage and on each init of your page check if the pagename equals the name in the sessionstorage. If not, you can clear it.




回答2:


For your particular case window events can be in handy. So you can react to the blur and focus events, so leaving your browser tab will cause blur event.

$(window).blur(function(){
  //clear session
});

$(window).focus(function(){
  //maybe some code to re-init session data
});


来源:https://stackoverflow.com/questions/41379849/how-to-clear-sessionstorage-when-navigating-to-another-page-but-not-on-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!