跨域通信:postMessage--小例子

原理

  • 利用postMessage不能和服务端交换数据,只能在两个窗口(iframe)之间交换数据
  • 两个窗口能通信的前提是,一个窗口以iframe的形式存在于另一个窗口,或者一个窗口是从另一个窗口通过window.open()或者超链接的形式打开的(同样可以用window.opener获取源窗口)

例子

index.html

<!doctype html>
<html>

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

<body>

    <form id="form">
        <input type="text" placeholder="Enter message" name="message" autocomplete="off">
        <input type="submit" value="Click to send">
    </form>

    <iframe src="./iframe.html" id="iframe" style="display:block;height:300px"></iframe>

    <script>
        form.onsubmit = function () {
            iframe.contentWindow.postMessage(this.message.value, 'http://localhost:3000/iframe.html');
            return false;
        };
    </script>

</body>

</html>

iframe.html

<!doctype html>
<html>

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

<body>

    <div id="showhere"></div>
    Receiving iframe.
    <script>
        window.addEventListener('message', function (event) {
            console.log(`Received ${event.data} from ${event.origin}`);
            document.getElementById('showhere').innerHTML += event.data;
        });
    </script>

</body>

</html>

 

猜你喜欢

转载自blog.csdn.net/weixin_41900808/article/details/88200049
今日推荐