51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

iframe下localStorage禁止访问。“Failed to read the localStorage property from Window”

# 问题原因 {#问题原因}

  • 浏览器开启"阻止第三方Cookie"

  • iframe内嵌页面使用 localStorage 则会出现js报错,导致页面无法正常展示

    Uncaught DOMException: Failed to read the 'localStorage' property from 'Window': Access is denied for this document.

# 解决方案 {#解决方案}

try {
  window._localStorage = window.localStorage
} catch() {
  window._localStorage = {
    getItem: function(key) { return '' },
    setItem: function(key, value) {},
    removeItem: function(key) {},
    clear: function() {},
  }
}

// 使用
_localStorage.getItem('key')
_localStorage.setItem('key', 'value')
_localStorage.removeItem('key')
_localStorage.clear()
赞(0)
未经允许不得转载:工具盒子 » iframe下localStorage禁止访问。“Failed to read the localStorage property from Window”