iframe postMessage跨域传参

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>

		<iframe src="http://xiawenyi/index.html" id="ifr" width="" height=""></iframe>
		<br />
		<br />
		<input type="text" name="" id="clickMe"  onclick="alert('clicked');" value="" placeholder="输入内容" />
		<button>写入iframe</button>

		<script>
			
			var buton = document.getElementsByTagName("button")[0]

			buton.onclick = function() {
				 var e = document.createEvent("MouseEvents");
				 var ifr = document.getElementById('ifr');
				 var targetOrigin = 'http://xiawenyi';
				 var url = window.location.href;
				 //通过ifrmae的contentWindow获取到iframe的window对象,通过postmessage向其发送数据消息
				 ifr.contentWindow.postMessage(url, targetOrigin);
			}
			window.addEventListener('message', function(event) { //给当前window建立message监听函数
				// 通过origin属性判断消息来源地址
				if (event.origin == 'http://xiawenyi') {
					alert(event.data); // 弹出"数据内容"
					console.log(event)
				}
			}, false);
		</script>
	</body>
</html>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>

        <input type="" name="" id="" value="" />
        <br />
        <br />
        <button target="" title="">将数据传给parent页面</button>

        <script>
                var inpt=document.getElementsByTagName("input")[0];

                window.addEventListener('message', function(event){
                    if (event.origin == 'http://xia') {
                        inpt.setAttribute("placeholder",event.data)
						alert(event.data);
						console.log(event)
                    }
                }, false);

                var a=document.getElementsByTagName("button")[0];
                a.onclick=function(){
                    var targetOrigin = 'http://xia';
					var url = window.location.href;
                    window.parent.postMessage(url, targetOrigin);
                }

        </script>
    </body>
</html>

你可能感兴趣的:(js)