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

iPhone端浏览器重启后localStorage值丢失问题求助

问题

参照示例实现localStorage功能,将页面及JS代码部署到Nginx和Node.js后端后,在iPhone的Safari和Chrome浏览器中,关闭浏览器后localStorage数据会丢失,但原示例网站的数据可正常保留。已尝试HTTP、HTTPS协议,更换不同后端,且代码与示例逐行一致,使用整数、文本值均出现该问题,请问该如何解决?

代码片段

HTML代码

<!DOCTYPE html>
<html>
<head>
<title>Test localStorage and sessionStorage persistence</title>
</head>
<body>
<h1>Local storage:<br />
<input type="text" placeholder="nothing currently stored" size="20" id="local" />
<input type="button" onclick="store_it('local' window.localStorage);" value="Store it" />
</h1>
<h1 id="local-warning">___</h1>
<script type="text/javascript" src="/public/storage-test.js"></script>
</body>
</html>

JavaScript代码

function store_it(id, storageArea) {
    var textBox = document.getElementById(id);
    if (!textBox.value) {
        delete storageArea.theirValue;  // don't store empty string, delete it instead
        window.alert('5 effacé  ')
    }
    else {
        storageArea.theirValue = textBox.value;
        console.log('6')
        window.alert('Done : ' + textBox.value)
    }
}

function retrieve_storage(id, storageArea) {
    var val = storageArea.theirValue;
    window.alert('14 retrieve_storage : ' + val)
    console.log('14 ', val)
    if (val != null)
        document.getElementById(id).value = val;
}

if (window.localStorage) {
    window.alert('20 Yes')
    retrieve_storage("local", window.localStorage);
}
else {
    window.alert('24 NO')
    document.getElementById("local-warning").innerHTML = "Note: this browser does not support localStorage";
}

排查与解决方案

  • 修复函数调用的语法错误:HTML中按钮的onclick事件代码store_it('local' window.localStorage);缺少参数分隔逗号,应改为store_it('local', window.localStorage);。这个语法错误会导致点击按钮时无法执行存储逻辑,看似弹出成功提示,实则未写入任何数据。
  • 检查iOS浏览器隐私设置:
    • Safari:进入「设置」→「Safari浏览器」→「隐私与安全性」,确认未开启「阻止所有Cookie」,同时关闭「离开后清除历史记录」选项。
    • Chrome:进入Chrome设置→「隐私和安全」→「Cookie和网站数据」,关闭「禁止网站保存和读取Cookie数据」及「关闭Chrome时清除Cookie和网站数据」选项。
  • 改用标准localStorage API:替换直接操作属性的方式为标准API,兼容性更稳定:
    // 存储数据
    storageArea.setItem('theirValue', textBox.value);
    // 读取数据
    var val = storageArea.getItem('theirValue');
    // 删除数据
    storageArea.removeItem('theirValue');
    
  • 验证存储操作结果:在存储代码后添加验证逻辑,确认数据已写入:
    storageArea.setItem('theirValue', textBox.value);
    console.log('存储验证:', storageArea.getItem('theirValue'));
    
  • 排查后端缓存策略:确认Nginx/Node.js未设置Cache-Control: no-store等极端缓存头,这类设置虽不直接影响localStorage,但可能导致页面异常加载间接引发问题。

内容的提问来源于stack exchange,提问作者Frederic J.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 21:12:52