iframe 跨域之间共享localStorage,sessionStorage

 

如:aaa.com 中读取bbb.com的localStorage

9-1 实现原理:

1-1.在aaa.com的页面中,在页面中嵌入一个src为bbb.com的iframe,此时这个iframe里可以调用bbb.com的localStorage。

1-2.用postMessage方法实现页面与iframe之间的通信。

综合1、2便可以实现aaa.com中调用bbb.com的localStorage

9-2优化iframe:

2-1我们可以在bbb.com中写一个专门负责共享localStorage的页面,例如叫做page1.html,这样可以防止无用的资源加载到iframe中。

9-3 示例:

3-1 以在aaa.com中读取bbb.com中的localStorage的item1为例,写同理:

bbb.com中page1.html,监听aaa.com通过postMessage传来的信息,读取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>

3-2 在aaa.com的页面中加入一个src为bbb.com/page1.html隐藏的iframe。

<iframe id="bbb-iframe" src="https://bbb.com/page1.html" style="display:none;"></iframe>

3-3 在aaa.com的页面中加入下面script标签。在页面加载完毕时通过postMessage告诉iframe中监听者,读取item1。监听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>

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值