gpt4 book ai didi

javascript - HTML5 localStorage.setItem 不适用于 iOS 8 - Safari 移动版

转载 作者:行者123 更新时间:2023-11-30 10:04:23 26 4
gpt4 key购买 nike

localStorage.setItem 不适用于移动 iOS 8.3。

有人遇到过这个问题吗?
这是代码:

var storage = window.localStorage;
storage.setItem('test',45);
alert(storage.getItem('test'));

最佳答案

过去,我们可以使用类似的东西:

if ('localStorage' in window && window.localStorage !== null) {
alert('can use');
}else{
alert('cannot use');
}

if (localStorage === undefined) {... }

但是,在 iOS 8.3+ 中,当用户禁用 cookie 时,这段代码会抛出一个未处理的 JavaScript 错误。当用户进入隐私浏览模式时,当您尝试写入 localStorage 时会出现相同的错误消息。

SecurityError: DOM Exception 18: An attempt was made to break through the security policy of the user agent.



解决方法

为了避免由于 iOS 的这种特殊行为而导致的不必要的 JavaScript 错误,一个建议是将其包含在 try catch block 中。 (至少目前)

try{
if ('localStorage' in window && window.localStorage !== null) {
localStorage.setItem('testLocalStorage', 'testLocalStorage');
if (localStorage.getItem('testLocalStorage') !== 'testLocalStorage') {
localStorage.removeItem('testLocalStorage');
//for private browsing, error is thrown before even getting here
alert('can read CANNOT write');
}else{
localStorage.removeItem('testLocalStorage');
alert('can use');
}
}else{
alert('CANNOT use');
}
}catch(ex){
alert('CANNOT use reliably');
}

注意:这不是建议在您的实际代码中使用警报。这只是为了快速说明。



可能的缩写

try {
localStorage.setItem('testLocalStorage', 'testLocalStorage');
localStorage.removeItem('testLocalStorage');
alert('supported');
} catch(ex) {
alert('unsupported');
}



我们可以用什么来代替

对于不支持 localStorage 的场景,可能的替代方案包括服务器 session (如果不支持 cookie,则基于 URL 参数)或用于存储序列化数据的 window.name 变量。

或者,如果您将设计和构建为单页应用程序,也许您根本不需要将数据存储在全局命名空间中。

关于javascript - HTML5 localStorage.setItem 不适用于 iOS 8 - Safari 移动版,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30048009/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com