【问题标题】:HTML5 localStorage.setItem is not working on iOS 8 - Safari mobileHTML5 localStorage.setItem 在 iOS 8 上不起作用 - Safari 移动版
【发布时间】:2016-09-20 09:35:08
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript local-storage ios8.3


    【解决方案1】:

    过去,我们可以这样使用:

    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: 试图突破 用户代理的安全策略。



    解决方法

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

    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 的场景,可能的替代方案包括服务器会话(如果不支持 cookie,则基于 URL 参数),或用于存储序列化数据的 window.name 变量。

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

    【讨论】:

      【解决方案2】:

      在使用之前,您应该使用if ('localStorage' in window && window.localStorage !== null) { ... 之类的代码检查localStorage 是否可用。

      【讨论】:

      • 我想解决问题而不是避免它。有没有类似的功能可以代替localStorage?
      • 我不是 ios safari 专家,也许是 cookie?
      猜你喜欢
      • 2014-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-28
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多