浅谈localStorage跨域的解决方案——postMessage和iframe

本文详细介绍了HTML5中postMessage方法的使用,包括其如何实现跨文本档、多窗口及跨域的消息传递。通过实例展示了父窗口与iframe之间的数据交换,以及不同源窗口间的安全通信机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

postMessage(data,origin)方法允许来自不同源的脚本采用异步方式进行通信,可以实现跨文本档、多窗口、跨域消息传递。接受两个参数:

① data:要传递的数据,html5规范中提到该参数可以是JavaScript的任意基本类型或可复制的对象,然而并不是所有浏览器支持任意类型的参数,部分浏览器只能处理字符串参数,所以在传递参数时需要使用JSON.stringify()方法对对象参数序列化。

② origin:字符串参数,指明目标窗口的源,协议+主机+端口号[+URL],URL会被忽略,所以可以不写,只是为了安全考虑,postMessage()方法只会将message传递给指定窗口,当然也可以将参数设置为"*",这样可以传递给任意窗口,如果要指定和当前窗口同源的话设置为"/"。

<!DOCTYPE html>  
<html>  
    <head>  
        <title></title>  
    </head>  
    <body>  
        <div style="width:200px; float:left; margin-right:200px;border:solid 1px #333;">  
            <div id="color">Frame Color</div>  
            </div>  
        <div>  
        <iframe id="child" src="http://127.0.0.1:8848/%E6%B5%8B%E8%AF%95/s.html"></iframe>  
        </div>  
        <script type="text/javascript">  
            window.onload = function() {  
				// 在页面加载完成后主页面向iframe发送getColor请求(参数没实际用处)
                window.frames[0].postMessage('getcolor', 'http://127.0.0.1:8848');  
				console.log('getcolor','发送父数据')
            }  
			// 主页面监听message事件,初始化自身颜色
			// 主页面监听message事件,处理自身变色
            window.addEventListener('message', function(e) {  
                var color = e.data;  
				console.log('接受子数据',e.data)
                document.getElementById('color').style.backgroundColor = color;  
            }, false);  
        </script>  
    </body>  
</html>
<!doctype html>
<html>
	<head>
		<style type="text/css">
			html,body{
				height:100%;
				margin:0px;
			}
		</style>
	</head>
	<body style="height:100%;">
		<div id="container" οnclick="changeColor();" style="widht:100%; height:100%; background-color:rgb(204, 102, 0);">
			click to change color
		</div>
		<script type="text/javascript">
			var container = document.getElementById('container');
			// iframe接收消息,并把当前颜色发送给主页面
			window.addEventListener('message', function(e) {
				
				if (e.source != window.parent) 
					return;
					console.log(e.data,'接收父数据')
				var color = container.style.backgroundColor;
				window.parent.postMessage(color, '*');
				console.log(color,'传递子数据')
			}, false);
			// 点击iframe时触发changeColor方法,把变化后的颜色发送给主页面
			function changeColor() {     
				var color = container.style.backgroundColor;
				if (color == 'rgb(204, 102, 0)')
					color = 'rgb(204, 204, 0)';
				else
					color = 'rgb(204,102,0)';
				container.style.backgroundColor = color;
				window.parent.postMessage(color, '*');
			}
		</script>
	</body>
</html>

 

关于postMessage

window.postMessage虽然说是html5的功能,但是支持IE8+,假如你的网站不需要支持IE6和IE7,那么可以使用window.postMessage。关于window.postMessage,很多朋友说他可以支持跨域,不错,window.postMessage是客户端和客户端直接的数据传递,既可以跨域传递,也可以同域传递。

应用场景

我只是简单的举一个应用场景,当然,这个功能很多地方可以使用。

假如你有一个页面,页面中拿到部分用户信息,点击进入另外一个页面,另外的页面默认是取不到用户信息的,你可以通过window.postMessage把部分用户信息传到这个页面中。(当然,你要考虑安全性等方面。)

发送信息:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<script>
			//弹出一个新窗口
		var domain = 'http://127.0.0.1:8848';
		var myPopup = window.open(domain 
					+ '/测试/d.html','myWindow');
		 
		//周期性的发送消息
		setTimeout(function(){
			//var message = '当前时间是 ' + (new Date().getTime()); 
				var message = {name:"站点",sex:"男"}; //你在这里也可以传递一些数据,obj等
			console.log('传递的数据是  ' + message);
			myPopup.postMessage(message,domain);
		},1000);
		</script>
	</body>
</html>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<script>
			//监听消息反馈
			window.addEventListener('message',function(event) {
				if(event.origin !== 'http://127.0.0.1:8848') return; //这个判断一下是不是我这个域名跳转过来的
				console.log('received response:  ',event.data);
			},false);
		</script>
	</body>
</html>

接受信息页面

 

如果是使用iframe,代码应该这样写:

//捕获iframe
var domain = 'http://haorooms.com';
var iframe = document.getElementById('myIFrame').contentWindow;
 
//发送消息
setTimeout(function(){
    //var message = '当前时间是 ' + (new Date().getTime()); 
        var message = {name:"站点",sex:"男"}; //你在这里也可以传递一些数据,obj等
    console.log('传递的数据是:  ' + message);
        //send the message and target URI
    iframe.postMessage(message,domain); 
},1000);

接受数据

 
//响应事件
window.addEventListener('message',function(event) {
    if(event.origin !== 'http://haorooms.com') return;
    console.log('message received:  ' + event.data,event);
    event.source.postMessage('holla back youngin!',event.origin);
},false);

上面的代码片段是往消息源反馈信息,确认消息已经收到。下面是几个比较重要的事件属性:

source – 消息源,消息的发送窗口/iframe。

origin – 消息源的URI(可能包含协议、域名和端口),用来验证数据源。

data – 发送方发送给接收方的数据。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值