H5中用postMessage传递数据,解决localStorage不能跨域问题

时间:2022-03-26 16:37:56

localStorage不能跨域,所以在A域名下用localStorage.YourKey方式存储的值,在B域名下是不能取到的。

所以需要转变思路,目前主要使用的两种方式:

一种方式:在A、B两个页面使用document.domain设置为相同的域名,但两个页面需要遵循同源策略,即协议,端口(如果有指定)和域名都相同;在根域范围内,允许把domain属性的值设置为它的上一级域。

另一种方式是推荐方式:在A域下,用postMessage方法把需要保存的数据传递过去,再在B域下接收并保存。postMessage可以安全地实现跨源通信。

postMessage方式实现步骤如下:

一、发送端sendpage.html(在 a.domain.com域名下):

1、sendpage.html中,添加一个iframe,src属性指定接收页面的url:

<iframe id="receivePage" src="http://b.domain.com/receive.html"></iframe>

2、sendpage.html中,在js中添加postMessage方法:

document.getElementById("receivePage").contentWindow.postMessage("要传递的数据","*");

二、接收端receive.html(在b.domain.com域名下):

<!doctype html>
<html>
<head>
</head>
<body style="height:100%;">
<script type="text/javascript">
window.addEventListener('message', function(e) {
if (e.source != window.parent)
return;
if(e.origin != "http://a.domain.com")//请求源验证
return;
localStorage.YourKey = e.data;
}, false);
</script>
</body>
</html>

postMessage参考