js postMessage demo

 

 

npm i http-server -g

http-server -p 8881


http://localhost:8881/

 

 

main.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>main</title>
</head>
<body>
    <p>main
        <button id="btn1">发送消息</button>
    </p>

    <iframe id="iframe1" src="./child.html" frameborder="1"></iframe>

    <script>
        document.getElementById('btn1').onclick = function () {
            window.iframe1.contentWindow.postMessage('hello', '*');
        };


        window.addEventListener('message', function (e) {
            console.log('main received',e.data);
        });
    </script>
</body>
</html>

 

 

 

 

 

child.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>child</title>
</head>
<body>
    <p>child

        <button id="btn1">发送消息</button>


    </p>


    <script>
        document.getElementById('btn1').onclick = function () {

            window.parent.postMessage('aaang', '*');

        };

        window.addEventListener('message', function (e) {

            console.log('child received',e.data);

        });

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

 

posted @ 2023-05-06 08:20  AngDH  阅读(61)  评论(0编辑  收藏  举报