window.postMessage的使用案例

本文主要是针对window.postMessage的使用

场景简述:父页面使用iframe嵌套了一个子页面,子页面操作后需要将数据返回父页面进行展示,父页面接收到消息后告诉子页面已经接收到消息。

 window.postMessage的参数介绍

otherWindow.postMessage(message, targetOrigin, [transfer]);
  1.  otherWindow:其他窗口的一个引用,比如iframe的contentWindow属性、执行window.open返回的窗口对象、或者是命名过或数值索引的window.frames。
  2. message:将要发送到其他 window的数据。
  3. targetOrigin:通过窗口的origin属性来指定哪些窗口能接收到消息事件,其值可以是字符串"*"(表示无限制)或者一个URI。
  4. transfer(可选参数):是一串和message 同时传递的 Transferable 对象,这些对象的所有权将被转移给消息的接收方,而发送一方将不再保有所有权。

 1、parent.html

        1、接收数据:监听message事件

        2、使用iframe的contentWindow属性向子页面发送消息。

<!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>展示消息</title>
    <style>
        #parent {
            width: 400px;
            border: 1px solid #000;
        }
    </style>
</head>

<body>
    <div id="parent">
        <div>
            <span>我是父页面:</span>
            <span id="text"></span> // 用于展示子页面传递的内容
        </div>
        <iframe id="chile" src="http://127.0.0.1:5500/chile.html" frameborder="0"></iframe>
    </div>
    <script>
        const ifram = document.getElementById("chile");
        const text = document.getElementById('text');
        // 子页面
        chile.onload = () => {
            window.addEventListener('message', event => {
                console.log("message", event);
                const data = event.data.res;
                text.innerText = data;
                const params = {
                    res: "父页面已经收到消息"
                }
                chile.contentWindow.postMessage(params, '*')
            }, false)
        }
    </script>
</body>

</html>

2、chile.html 

        1、使用 window.parent.postMessage(data, '*');发送数据。

<!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>发送消息</title>
    <style>
        #chile {
            height: 50px;
            border: 1px solid #000;
        }
    </style>
</head>

<body>
    <div id="chile">
        <div>
            <span>我是子页面:</span>
            <span id="chileText"></span> // 用于展示父页面传递发内容
        </div>
        <button id="chileBtn">点击发送</button>
    </div>
    <script>
        const chileBtn = document.getElementById("chileBtn");
        const chileText = document.getElementById("chileText");
        chileBtn.onclick = () => {
            const params = {
                res: "我来自子页面"
            }
            window.parent.postMessage(params, "*")
        }

        window.addEventListener("message", event => {
            console.log('chile---message---', event);
            chileText.innerText = event.data.res;
        }, false)
    </script>
</body>

</html>

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
`window.parent.postMessage` 是用于在嵌套的 iframe 中向父级窗口发送消息的方法。下面是一个详细的案例,演示了如何使用 `window.parent.postMessage` 进行跨域通信。 假设我们有一个父级页面(`parent.html`)和一个嵌套的 iframe(`child.html`),它们分别位于不同的域名下。 在 `parent.html` 中: ```html <!DOCTYPE html> <html> <head> <title>Parent Page</title> </head> <body> <h1>Parent Page</h1> <iframe src="http://child-domain.com/child.html" id="childFrame"></iframe> <script> // 监听来自 iframe 的消息 window.addEventListener("message", receiveMessage, false); function receiveMessage(event) { // 确保消息来自特定域名 if (event.origin !== "http://child-domain.com") { return; } console.log("Received message from child iframe: " + event.data); // 在这里可以进行相应的处理逻辑 } </script> </body> </html> ``` 在 `child.html` 中: ```html <!DOCTYPE html> <html> <head> <title>Child Page</title> </head> <body> <h1>Child Page</h1> <script> // 发送消息给父级页面 window.parent.postMessage("Hello from child iframe", "http://parent-domain.com"); </script> </body> </html> ``` 在这个例子中,父级页面 `parent.html` 包含一个嵌套的 iframe,其中的 `src` 属性指向 `child.html`,并且指定了 `id` 为 `childFrame`。在父级页面的 JavaScript 中,我们使用 `window.addEventListener` 来监听来自 iframe 的消息。当收到消息时,我们检查消息的来源域名,确保它来自特定的域名(在这个例子中是 `http://child-domain.com`),然后进行相应的处理逻辑。 在子级页面 `child.html` 的 JavaScript 中,我们使用 `window.parent.postMessage` 发送消息给父级页面。第一个参数是要发送的消息内容,第二个参数是接收消息的页面的域名(在这个例子中是 `http://parent-domain.com`)。 通过这种方式,我们实现了从嵌套的 iframe 页面向父级页面发送跨域消息,并在父级页面中接收和处理这些消息。 请注意,为了安全考虑,需要在接收消息的页面中检查消息的来源域名,并且只接受来自特定域名的消息。这可以防止恶意代码发送虚假消息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

瘦小橘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值