概述`postMessage` 提供跨上下文通信能力,必须设置精确的 `targetOrigin`,并在接收端验证 `event.origin` 与数据结构,避免被恶意页面利用。可与 Transferable 传递大数据提高效率。示例// 发送端 otherWindow.postMessage({ type: 'update', payload: { id: 1 } }, 'https://trusted.example') // 接收端 window.addEventListener('message', e => { if (e.origin !== 'https://trusted.example') return if (typeof e.data !== 'object' || e.data?.type !== 'update') return // 处理消息 }) 工程建议最小权限:限制 `targetOrigin` 与可通信窗口;在沙箱 iframe 使用严格 `sandbox/allow`。数据校验:使用模式校验或类型系统;忽略未知消息类型。兼容与性能:对大对象使用 Transferable;管理生命周期与释放。参考与验证MDN `postMessage` 文档:https://developer.mozilla.org/docs/Web/API/Window/postMessageHTML 规范(跨文档消息):https://html.spec.whatwg.org/

发表评论 取消回复