Categories: Browser对象tips

Window postMessage() 方法 | Window 对象

返回到:Browser 对象:Window 对象

定义和用法

postMessage() 方法用于安全地实现跨源通信。

语法

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

所有主要浏览器都支持 postMessage() 方法

实例

DEMO1:发送程序。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Web176教程(Web176.com)</title>
</head>
<body>
<div>
    <input id="text" type="text" value="Runoob" />
    <button id="sendMessage" >发送消息</button>
</div>
<iframe id="receiver" src="https://www.Web176.com" width="300" height="360">
    <p>你的浏览器不支持 iframe。</p>
</iframe>
<script>
window.onload = function() {
    var receiver = document.getElementById('receiver').contentWindow;
    var btn = document.getElementById('sendMessage');
    btn.addEventListener('click', function (e) {
        e.preventDefault();
        var val = document.getElementById('text').value;
        receiver.postMessage("Hello "+val+"!", "https://www.Web176.com");
    });
}
</script>
</body>
</html>

DEMO2:接收程序有一个事件监听器,监听 “message” 事件,同时我们要验证消息来源地址,以确保是个可信的发送地址。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Web176教程(Web176.com)</title>
</head>
<body>
<div>
    <input id="text" type="text" value="Runoob" />
    <button id="sendMessage" >发送消息</button>
</div>
<iframe id="receiver" src="https://www.web176.com" width="300" height="360">
    <p>你的浏览器不支持 iframe。</p>
</iframe>
<script>
window.onload = function() {
    var receiver = document.getElementById('receiver').contentWindow;
    var btn = document.getElementById('sendMessage');
    btn.addEventListener('click', function (e) {
        e.preventDefault();
        var val = document.getElementById('text').value;
        receiver.postMessage("Hello "+val+"!", "https://www.web176.com");
    });
}
</script>
</body>
</html>
  • e.source – 消息源,消息的发送窗口/iframe。
  • e.origin – 消息源的 URI(可能包含协议、域名和端口),用来验证数据源。
  • e.data – 发送过来的数据。
terry

这个人很懒,什么都没有留下~

Share
Published by
terry

Recent Posts

聊聊vue3中的defineProps

在Vue 3中,defineP…

1 周 ago

在 Chrome 中删除、允许和管理 Cookie

您可以选择删除现有 Cooki…

2 周 ago

自定义指令:聊聊vue中的自定义指令应用法则

今天我们来聊聊vue中的自定义…

3 周 ago

聊聊Vue中@click.stop和@click.prevent

一起来学下聊聊Vue中@cli…

4 周 ago

Nginx 基本操作:启动、停止、重启命令。

我们来学习Nginx基础操作:…

4 周 ago

Vue3:手动清理keep-alive组件缓存的方法

Vue3中手动清理keep-a…

1 月 ago