天天看点

iframe 获取父窗口 调用方法 跨域关键代码获取子窗口 (反过来就好了)

假设有一个 http://localhost:8080/项目下的 parent.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">

    <script>
        function load() {
            window.addEventListener("message",function(event){
	            console.log(event);
	            hello();
        	});
        }
        function hello() {
             console.log("你好");
        }

    </script>

</head>

<body onload="load()">
	<iframe src="http://dev.xcall.cn:8090/child.html"></iframe>
</body>

</html>

           

http://dev.xcall.cn:8090/项目下的 child.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">

    <script>
        function submitHandler() {
             window.parent.postMessage("closeAndRefresh",'http://localhost:8080/')

        });
        }

    </script>

</head>

<body>
 <button onclick="submitHandler()">提交申请</button>

</body>

</html>

           

关键代码

window.addEventListener("message",function(event){
	            console.log(event);
        	});


  window.parent.postMessage("closeAndRefresh",'http://localhost:8080/')
  
           

获取子窗口 (反过来就好了)

document.getElementsByName("layui-layer-iframe1")[0].contentWindow;
 或者 
let win= document.getElementById("layui-layer-iframe1").contentWindow;

win.parent.postMessage("closeAndRefresh",'http://dev.xcall.cn:8090/')