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

如何修改localStorage逻辑实现不同页面独立存储阅读进度

问题根源

你当前的问题出在localStorage的API使用逻辑错误:

  • localStorage.setItem(key, value) 仅接收2个有效参数,你额外传入的url_string不会被识别,所有页面都共用固定key last存储进度,自然会出现跨页面进度串掉的问题。
  • 读取时localStorage.getItem(key)也仅接收1个key参数,你传的第二个url参数同样无效,所以不管打开哪个页面,读取的都是同一个全局存储的进度值。

修复方案

把当前页面的唯一标识作为存储key的一部分,保证每个页面对应独立的存储空间,修复后代码如下:

<script>
// 生成当前页面专属的存储key
function getPageUniqueKey() {
  // 可以根据需求调整规则,比如不需要锚点的话可以去掉window.location.hash
  return 'read_progress_' + window.location.href;
}

window.onunload = function() {
  const currentPage = document.getElementById("pageNumber").value;
  localStorage.setItem(getPageUniqueKey(), currentPage);
};

window.onload = function() {
  const savedPage = localStorage.getItem(getPageUniqueKey());
  if (savedPage) {
    document.getElementById("pageNumber").value = savedPage;
    window.location.href = "#" + savedPage;
  }
};
</script>

可选优化

如果你的页面URL会带上不影响内容的参数(比如推广来源、统计参数等),可以调整key生成规则,避免同一个内容页面生成多个存储记录:

function getPageUniqueKey() {
  // 仅取路径+内容相关查询参数,过滤掉无关参数和锚点
  return 'read_progress_' + window.location.pathname + window.location.search;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:15:01