iframe 跨域通信用 postMessage,并且必须校验来源 origin

父页面和 iframe 跨域拿不到彼此变量,只能靠 postMessage 通信。

发送时第二个参数要写目标域,不要图省事直接传星号。

接收端必须校验 event.origin 是否在白名单内,否则任意页面都能灌数据。

// 父 → 子
iframe.contentWindow.postMessage({ type: 'sync' }, 'https://child.example.com');
// 子 → 父
window.parent.postMessage({ type: 'ready' }, 'https://parent.example.com');
// 接收端必须校验来源
window.addEventListener('message', (e) => {
  if (e.origin !== 'https://child.example.com') return;
  handle(e.data);
});
THE END
喜欢就支持一下吧
点赞13 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容