浏览器实现跨系统交互

发布于:2025-06-20 ⋅ 阅读:(20) ⋅ 点赞:(0)

浏览器实现跨系统交互

浏览器中通过 iframe 嵌入另一个系统,并实现跨系统消息交互的详细系统讲解,包括原理、安全机制、实现流程、使用场景以及常见问题的全面说明

感兴趣的可以关注一下,会不定期分享一些实用笔记https://mp.weixin.qq.com/s/d12PcS16VUeXfylvUlkD1g

🧠 一、系统整体结构与原理

💡 1.1 基本结构

假设系统 A 通过iframe标签嵌入系统 B

<!-- 系统 A 页面 -->
<iframe src="https://system-b.com/page.html" id="myFrame"></iframe>

此时浏览器中就有两个独立的页面:

  • 外部父页面:系统 A
  • 内嵌子页面:系统 B

这两个页面通常是**不同源(跨域)**的,浏览器会强制阻止它们直接互访 DOM 或脚本资源。

🔒 1.2 浏览器同源策略(SOP)

同源策略(Same-Origin Policy)限制:

  • 如果两个页面协议、主机名、端口号任一不同,就被认为是不同源
  • 不同源的 iframe 无法直接访问 document、window、cookie 等对象
⛔ 错误示例(会报错)
let iframe = document.getElementById("myFrame");
let doc = iframe.contentWindow.document; // ❌ 跨域会报错

📬 1.3 安全通信机制:window.postMessage

HTML5 引入了 window.postMessage(),允许跨源通信:

  • 不需要同源
  • 可用于 window、iframe、popup、worker 等之间通信

🛠️ 二、通信实现流程

✅ 2.1 iframe 向父页面发送数据

// system-b.com/page.html
window.parent.postMessage(
  {
   
    type: "formSubmit",
    data: {
    name: "Alice", age: 30 }
  },
  "https://system-a.com" // 安全校验目标
);

✅ 2.2 父页面接收消息

// system-a.com/index.html
window.addEventListener("message", (event) => {
   
  // 校验来源(安全性)
  if (event.origin !== "https://system-b.com") return;

  // 处理消息
  const msg = event.data;
  if (msg.type === "formSubmit") {
   
    console.log("收到表单数据:", msg.data);
  }
});

🔐 三、安全机制详解

🔎 3.1 校验 event.origin

绝对不能省略,否则容易被其他恶意网站注入数据

if (event.origin !== "https://trusted.com") return;

🧱 3.2 指定 targetOrigin

当调用 postMessage 时,第二个参数一定不要写成 ‘*’,应指明目标源

window.parent.postMessage(data, "https://trusted-parent.com");

🔐 3.3 不直接执行任何收到的数据

避免 XSS 攻击,收到的数据不要拼接进 HTML 或使用 eval() 执行

🧩 四、典型应用场景

应用场景 示例
第三方支付组件嵌入 微信/支付宝嵌入支付页面,通过 iframe 回传支付结果
登录认证 子系统嵌入父系统并通过 postMessage 回传 token
微前端架构通信 主应用与子应用之间传递状态、事件、消息
可视化平台组件传值 父系统向嵌入的地图组件传递筛选参数等

🧪 五、常见问题与解决方案

❓ 5.1 子页面 ready 但父页面未监听

确保父页面在 iframe 加载前就监听:

window

网站公告

今日签到

点亮在社区的每一天
去签到