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.
1
# 解决方案
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()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
上次更新: 2022-08-30 09:53:40