xb18
xb18
文章39
标签0
分类0
前端通信

前端通信

postMessage

可以跨域,可用于iframe间消息

发送消息

1
2
3
4
5
function postToMessage(action, data = null) {
window.parent.postMessage(JSON.stringify({ action, data }), '*');
// 发送至window.parent
}
// otherWindow.postMessage(message, targetOrigin, [transfer]);
  • otherWindow

    其他窗口的一个引用,比如 iframe 的 contentWindow 属性、执行 window.open 返回的窗口对象、或者是命名过或数值索引的 window.frames。

  • message

    要发送的数据。它将会被结构化克隆算法序列化,所以无需自己序列化(部分低版本浏览器只支持字符串,所以发送的数据最好用JSON.stringify()序列化)。

  • targetOrigin

    通过 targetOrigin 属性来指定哪些窗口能接收到消息事件,其值可以是字符串“*”(表示无限制)或者一个 URI(如果要指定和当前窗口同源的话可设置为”/“)。在发送消息的时候,如果目标窗口的协议、主机地址或端口号这三者的任意一项不匹配 targetOrigin 提供的值,那么消息就不会发送。

接收消息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
window.addEventListener("message", (event) => {
let { origin, data: dataOrg } = event;
if (origin === location.origin) {
let result = {};
try {
result = JSON.parse(dataOrg);
} catch (error) {
}
const { method, data } = result
if (!method) return;
console.log('method event', event);
if (method === 'log') {
console.log('data==log===>', data);
}
}
}, false);

event 的属性有:

  • data: 从其他 window 传递过来的数据副本。
  • origin: 调用 postMessage 时,消息发送窗口的 origin。例如:“http://example.com:8080”。
  • source: 对发送消息的窗口对象的引用。可以使用此来在具有不同 origin 的两个窗口之间建立双向数据通信

消息传递

1
2
3
4
// 可以向打开的window传递消息
const targetWindow = window.open('http://xxx');
// 可以与嵌套的ifrmae传递消息
const iframeWin = document.getElementById('iframe').contentWindow;

安全

  • 如果你不希望从其他网站接收 message,请不要为 message 事件添加任何事件监听器。
  • 如果你确实希望从其他网站接收message,请始终使用 origin 和 source 属性验证发件人的身份。
  • 当你使用 postMessage 将数据发送到其他窗口时,始终指定精确的目标 origin,而不是 *。

localstorage

监听localstorage变化

本文作者:xb18
本文链接:http://xb18.github.io/2023/10/23/%E5%89%8D%E7%AB%AF%E9%80%9A%E4%BF%A1/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可