[英]JavaScript Differentiate Between Page Refresh, Browser Close and New tab
我试图区分页面刷新、浏览器关闭和新标签事件。
所以,我想对页面关闭 V/s 页面刷新/新选项卡进行一些处理
我在使用 sessionStorage 时遇到了以下解决方法。 然而 sessionStorage 的问题是它会被重置或即使在新标签中打开链接也不会被读取。 但我希望页面刷新/新选项卡以相同的方式对页面进行 V/s 刷新。
if (sessionStorage.getItem('reloaded') != null) {
console.log('page was reloaded');
} else {
console.log('page was not reloaded');
}
sessionStorage.setItem('reloaded', 'yes');
您必须结合使用sessionStorage
和localStorage
来保存数据,并依靠beforeunload
事件来处理数据删除。
事情是beforeunload
在选项卡/窗口关闭和页面刷新时触发,所以我们必须解决这个问题。
localStorage
将处理跨选项卡和窗口的持久性, sessionStorage
将在页面刷新时同步数据。
const readFromStorage = (storageKey) => {
const localStorageItem = localStorage.getItem(storageKey);
const sessionStorageItem = sessionStorage.getItem(storageKey);
// You can optimize this by doing more checks but you get the idea
const itemValue = localStorageItem ?? sessionStorageItem;
if (localStorageItem !== sessionStorageItem) {
writeToStorage(storageKey, itemValue);
}
return itemValue;
};
const writeToStorage = (storageKey, value) => {
localStorage.setItem(storageKey, value);
sessionStorage.setItem(storageKey, value);
};
事件处理程序:
window.addEventListener('beforeunload', (e) => {
localStorage.removeItem(STORAGE_KEY);
});
用法:
const STORAGE_KEY = '<storage_key>';
const item = readFromStorage(STORAGE_KEY);
如果item
为null
- 选项卡/窗口已关闭。 否则,数据将在刷新和新选项卡/窗口中保持不变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.