Mapbox/MapLibre:如何持久化保存最新location.hash,解决页面切换失效问题
地图页面Hash保存问题及修复方案
当地图相机移动时,URL的hash会自动更新,我需要保存这个hash值,以便返回地图页面时能回到之前的位置。但用以下代码将hash存入sessionStorage后,切换到应用其他页面再返回时,sessionStorage会被重置为初始值,无法保留有效hash:
function initLocationHash () { let newHash = window.location.hash sessionStorage.setItem('locationHash', JSON.stringify(newHash)) } window.addEventListener('DOMContentLoaded', function () { let storedHash = JSON.parse(sessionStorage.getItem('locationHash')); if (storedHash) { window.location.hash = storedHash } console.log(storedHash, 'storedHash') }) setInterval(function () { let storedHash = JSON.parse(sessionStorage.getItem('locationHash')); let currentHash = window.location.hash if (currentHash !== storedHash) { initLocationHash() } }, 100)
问题原因分析
- 轮询逻辑缺陷:用
setInterval轮询判断hash变化,页面切换返回时初始hash为空,容易覆盖之前存储的有效hash值。 - 冗余序列化操作:hash本身是字符串,无需用
JSON.stringify和JSON.parse处理,多余操作可能引发意外问题。 - 触发时机不合理:DOMContentLoaded执行后,若页面初始hash为空,后续轮询会立即将空hash存入sessionStorage,覆盖之前的有效存储。
修复后的代码
// 保存当前hash到sessionStorage function saveLocationHash() { const currentHash = window.location.hash; // 仅保存非空hash,避免覆盖有效存储 if (currentHash) { sessionStorage.setItem('locationHash', currentHash); } } // 页面加载时恢复之前的hash window.addEventListener('DOMContentLoaded', function() { const storedHash = sessionStorage.getItem('locationHash'); // 仅当存储的hash存在且与当前hash不同时才设置 if (storedHash && window.location.hash !== storedHash) { window.location.hash = storedHash; } }); // 监听hash变化事件,实时保存 window.addEventListener('hashchange', saveLocationHash); // 页面完全加载后,保存初始hash(若存在) window.addEventListener('load', saveLocationHash);
修复说明
- 用
hashchange事件替代轮询:仅在hash真正发生变化时触发保存,性能更优且避免误判。 - 移除冗余序列化:直接存储hash字符串,减少不必要的处理步骤。
- 增加非空判断:避免将空hash存入sessionStorage,防止覆盖之前的有效值。
- 优化恢复逻辑:仅当存储的hash与当前hash不同时才设置,避免不必要的页面跳转。
内容的提问来源于stack exchange,提问作者Pavel
相关产品推荐
相关产品推荐

