-
Notifications
You must be signed in to change notification settings - Fork 2
/
storage.html
103 lines (85 loc) · 2.29 KB
/
storage.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>storage</title>
</head>
<body>
<script>
(function(){
if ( !('postMessage' in window) || !('localStorage' in window) ) return;
var sign = 'CROSS_STORAGE'
if ( 'addEventListener' in document ) {
window.addEventListener('message', handler, false);
}
else if ( 'attachEvent' in document ) {
window.attachEvent('onmessage', handler);
}
function handler (msg) {
if ( !(/\.huya\.com$/.test(msg.origin)) ) return;
var data = null
try {
data = JSON.parse(msg.data)
} catch (e) {}
// 拆包
if (data && data.sign === sign) {
action[data.type](data.data, data.token)
}
}
var action = {
set: function (data) {
for (var key in data) {
if ( data.hasOwnProperty(key) ) {
var val = data[key]
try {
val = JSON.stringify(val)
} catch(e) {}
localStorage.setItem(key, val)
}
}
},
get: function (key, token) {
var val = localStorage.getItem(key)
try {
val = JSON.parse(val)
} catch(e) {}
send(token, val)
},
del: function (key) {
key ? localStorage.removeItem(key) : localStorage.clear()
}
}
if (window.addEventListener) {
window.addEventListener('storage', function(e){
var oldValue = e.oldValue
var newValue = e.newValue
try {
oldValue = JSON.parse(oldValue)
} catch(e) {}
try {
newValue = JSON.parse(newValue)
} catch(e) {}
send('STORE_CHANGE', {
key: e.key,
oldValue: oldValue,
newValue: newValue
})
})
}
function send (token, data) {
var msg = ''
try {
msg = JSON.stringify({
sign: sign,
token: token,
data: data
})
} catch (e) {}
if (msg) {
parent.postMessage(msg, '*')
}
}
})()
</script>
</body>
</html>