HTML5 localStorage.setItem在iOS 8上不起作用-Safari移动版 [英] HTML5 localStorage.setItem is not working on iOS 8 - Safari mobile

查看:177
本文介绍了HTML5 localStorage.setItem在iOS 8上不起作用-Safari移动版的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

localStorage.setItem 在移动iOS 8.3上不起作用.

localStorage.setItem is not working on mobile iOS 8.3.

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

Does anybody experience this problem?
Here is the code:

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

推荐答案

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

In the past, we could use something like:

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

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

但是,在iOS 8.3+中,当用户禁用cookie 时,此代码将引发未处理的JavaScript错误.当用户进入私有浏览模式时,当您尝试写入localStorage时,也会出现相同的错误消息.

However, in iOS 8.3+, when the user disables cookies, this code throws an unhandled JavaScript error. And when the user goes into private browsing mode, that same error message appears when you try to write to localStorage.

SecurityError:DOM异常18:试图突破用户代理的安全策略.

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



解决方法

为避免由于iOS的这种特殊行为而导致不必要的JavaScript错误,一种建议是将其包含在try catch块中.(至少暂时如此)

To avoid unwanted JavaScript errors due to this particular behavior of iOS, one suggestion is to enclose it within try catch blocks. (at least for the time being)

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');
}

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

Note: This is not a suggestion to use alerts in your actual codes. It is just for a quick illustration.



可能的缩写

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



我们可以用什么代替

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

For scenarios where localStorage is not supported, possible alternatives include server sessions (based on URL parameters if cookies are not supported), or window.name variable to store the serialized data.

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

Or if you design and build as a Single Page App, perhaps you do not need to store data in the global namespace at all.

这篇关于HTML5 localStorage.setItem在iOS 8上不起作用-Safari移动版的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆