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

如何高效将某页面的URL变化同步至同设备的另一页面?

高效实现同源页面间的Hash变化同步

不用定期轮询localStorage,直接用hashchange事件配合Storage事件就能实现主动推送,性能更优:

1. 处理something.php的Hash变化

在something.php里监听自身的hash变化事件,一旦URL的#部分改变,就把最新值存到localStorage:

// something.php 代码
window.addEventListener('hashchange', () => {
    localStorage.setItem('currentPageHash', window.location.hash);
});

2. 在anything.php监听状态变更

在anything.php里监听storage事件,只要同源页面修改了localStorage,这个事件就会触发,直接拿到更新后的Hash:

// anything.php 代码
window.addEventListener('storage', (e) => {
    if (e.key === 'currentPageHash') {
        const newHash = e.newValue;
        // 这里写你收到Hash变化后的处理逻辑
        console.log('Hash更新了:', newHash);
    }
});

额外提示

  • Storage事件只会在其他同源页面触发,修改localStorage的something.php本身不会收到,刚好符合你的需求
  • 如果想要anything页面刚加载时就同步当前的Hash值,可以在页面加载时主动读一次localStorage:
    // anything.php 初始化代码
    window.addEventListener('load', () => {
        const initHash = localStorage.getItem('currentPageHash');
        if (initHash) {
            console.log('初始Hash值:', initHash);
            // 处理初始值逻辑
        }
    });
    

内容的提问来源于stack exchange,提问作者Real Noob

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 04:05:27