iframe的坑

通信例子

parent:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>MathJax v3 with interactive TeX input and HTML output</title>
    <script src="./js/jquery.min.js"></script>
</head>

<body>

    <iframe id="child" src='./child.html' width="800" height="600px" onload="echartIframeOnLoad()"></iframe>
    <script>
        function echartIframeOnLoad(e) {
            document.getElementById('child').contentWindow.postMessage(
                '我是你爸爸3',
                '*'
            );
        }
        $(function () {
            document.getElementById('child').contentWindow.postMessage(
                '我是你爸爸1',
                '*'
            );
        });
        setTimeout(() => {
            document.getElementById('child').contentWindow.postMessage(
                '我是你爸爸2',
                '*'
            );
        }, 500)
        window.addEventListener('message', function (e) {
            // console.log('收到消息,child说')
            var d = e.data;  //e.data  里面有自己所传的所有参数  可以根据参数做自己的判断
            console.log(d);
        }, false);
    </script>
    </script>
</body>

</html>

child:

<!DOCTYPE html>
<html style="height: 100%">

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

<body style="height: 100%; margin: 0">
    <script type="text/javascript">
        window.addEventListener('message', function (e) {
            var d = e.data;  //e.data  里面有自己所传的所有参数  可以根据参数做自己的判断
            top.postMessage(
                {
                    mess: d,
                    from: 'child'
                },
                '*'
            );
        });
    </script>
</body>

</html>

结果:

 消息 "我说你爸爸1"一定收不到。"我是你爸爸2",当网速很差的时候,也收不到。 所以,父窗口一定要等到iframe加载完成后,才能发送消息!

猜你喜欢

转载自www.cnblogs.com/xunhanliu/p/12180540.html
今日推荐