問(wèn)題
兩個(gè)不同的域名的localStorage不能直接互相訪問(wèn)俩块。那么如何在aaa.com
中如何調(diào)用bbb.com
的localStorage?
實(shí)現(xiàn)原理
1.在aaa.com
的頁(yè)面中欲低,在頁(yè)面中嵌入一個(gè)src為bbb.com
的iframe
,此時(shí)這個(gè)iframe
里可以調(diào)用bbb.com
的localStorage。
2.用postMessage
方法實(shí)現(xiàn)頁(yè)面與iframe
之間的通信。
綜合1淀弹、2便可以實(shí)現(xiàn)aaa.com
中調(diào)用bbb.com
的localStorage。
優(yōu)化iframe
我們可以在bbb.com
中寫(xiě)一個(gè)專門(mén)負(fù)責(zé)共享localStorage的頁(yè)面洪添,例如叫做page1.html
垦页,這樣可以防止無(wú)用的資源加載到iframe
中雀费。
示例
以在aaa.com
中讀取bbb.com
中的localStorage的item1
為例干奢,寫(xiě)同理:
bbb.com
中page1.html
,監(jiān)聽(tīng)aaa.com
通過(guò)postMessage
傳來(lái)的信息盏袄,讀取localStorage忿峻,然后再使用postMessage
方法傳給aaa.com
的接收者。
<!DOCTYPE html>
<html lang="en-US">
<head>
<script type="text/javascript">
window.addEventListener('message', function(event) {
if (event.origin === 'https://aaa.com') {
const { key } = event.data;
const value = localStorage.getItem(key);
event.source.postMessage({wallets: wallets}, event.origin);
}
}, false);
</script>
</head>
<body>
This page is for sharing localstorage.
</body>
</html>
在aaa.com
的頁(yè)面中加入一個(gè)src為bbb.com/page1.html
隱藏的iframe
辕羽。
<iframe id="bbb-iframe" src="https://bbb.com/page1.html" style="display:none;"></iframe>
在aaa.com
的頁(yè)面中加入下面script標(biāo)簽逛尚。在頁(yè)面加載完畢時(shí)通過(guò)postMessage
告訴iframe
中監(jiān)聽(tīng)者,讀取item1
刁愿。監(jiān)聽(tīng)bbb.com
傳回的item1
的值并輸出绰寞。
<script type="text/javascript">
window.onload = function() {
const bbbIframe = document.getElementById('bbb-iframe');
bbbIframe.contentWindow.postMessage({key: 'item1'}, 'https://bbb.com');
}
window.addEventListener('message', function(event) {
if (event.origin === 'https://bbb.com') {
console.log(event.data);
}
}, false);
</script>