《js》iframe之间跨域交互

1. 父页面调用子页面

直接通过iframe的url?param=abc 方式, 把值传到子页面.

2. 子页面调用父页面

通过parent

3. window.postMessage()

该window.postMessage()方法安全地启用Window对象之间的跨源通信;例如,在页面和它产生的弹出窗口之间,或者在页面和嵌入其中的iframe之间。

通常,当且仅当它们源自的页面共享相同的协议、端口号和主机(也称为“同源策略”)时,允许不同页面上的脚本相互访问。window.postMessage()提供一种受控制的机制来安全地规避这种限制(如果使用得当)。

接收消息

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>接收消息</title>
</head>

<script>
    window.onload = function() {
        var messageEle = document.getElementById(message);
        window.addEventListener(message, function (e) {
            if (e.origin !== "http://localhost:8080") {
                return;
            }
            messageEle.innerHTML = "从"+ e.origin +"收到消息: " + e.data;
        });
    }
</script>

<body>

<div id="message">
    等待接收消息!
</div>
</body>
</html>

发送消息

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>给iframe发送消息</title>

<script>
	window.onload = function() {
		var receiver = document.getElementById(receiverIframe).contentWindow;
		var btn = document.getElementById(send);
		btn.addEventListener(click,
				function(e) {
					e.preventDefault();
					var val = document.getElementById(text).value;
					receiver.postMessage("Hello " + val + "!","http://localhost:8080");
				});
	}
</script>
</head>

<body>
	<div>
		<input id="text" type="text" value="你好吗?" />
		<button id="send">发送消息</button>
	</div>
	<iframe id="receiverIframe" src="http://localhost:8080/receiver" width="500" height="60">
		<p>你的浏览器不支持IFrame。</p>
	</iframe>
</body>
</html>
经验分享 程序员 微信小程序 职场和发展