You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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)

问题原因分析

  1. 轮询逻辑缺陷:用setInterval轮询判断hash变化,页面切换返回时初始hash为空,容易覆盖之前存储的有效hash值。
  2. 冗余序列化操作:hash本身是字符串,无需用JSON.stringify和JSON.parse处理,多余操作可能引发意外问题。
  3. 触发时机不合理: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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 07:52:48