好的,我们来对 iframe-message-bridge 项目进行升级,加入您提到的新功能:
- 消息序列号(防止重放攻击):每次发送消息时,都附带一个递增的序列号。接收方会记录已收到的最大序列号,并拒绝任何小于或等于该值的消息。
- 更复杂的消息类型和处理逻辑:使用
switch 语句来处理不同类型的消息,例如初始化、数据请求、事件通知等。
- 判断父页面是否存在:在子页面(iframe)加载时,检查它是否真的被嵌入在一个 iframe 中。如果不是,则显示提示信息,并且不执行通信逻辑。
下面是更新后的示例代码。
项目结构
code
iframe-message-bridge-v2/
├── parent.html # 父页面
├── child.html # 子页面
└── README.md # 项目说明
1. parent.html(父页面)
此版本增加了更丰富的交互按钮和一个用于显示通信日志的区域。
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Parent Page - iframe-message-bridge v2</title>
<style>
body { font-family: sans-serif; }
#log { background-color: #f0f0f0; border: 1px solid #ccc; padding: 10px; height: 200px; overflow-y: scroll; white-space: pre-wrap; }
</style>
</head>
<body>
<h1>Parent Page</h1>
<div>
<button onclick="initChild()">Initialize Child</button>
<button onclick="requestDataFromChild()">Request User Data from Child</button>
<br><br>
<input type="text" id="messageInput" placeholder="Enter simple message">
<button onclick="sendSimpleMessage()">Send Simple Message</button>
</div>
<h3>Communication Log:</h3>
<pre id="log"></pre>
<iframe id="childIframe" src="child.html" style="width: 100%; height: 300px; border: 1px solid #ccc;"></iframe>
<script>
const iframe = document.getElementById('childIframe');
const logElement = document.getElementById('log');
// --- 状态管理 ---
let sequenceId = 0; // 用于发送消息的序列号
let lastReceivedSequenceId = -1; // 已收到的最大序列号
const CHILD_ORIGIN = '*'; // !! 生产环境应替换为子页面的具体源,例如 'https://child.example.com'
// --- 通用日志记录 ---
function log(message) {
logElement.textContent += `${new Date().toLocaleTimeString()}: ${message}\n`;
logElement.scrollTop = logElement.scrollHeight;
}
// --- 通用消息发送函数 ---
function sendMessage(type, payload = {}) {
sequenceId++;
const message = {
type: type,
payload: payload,
sequenceId: sequenceId
};
iframe.contentWindow.postMessage(message, CHILD_ORIGIN);
log(`SENT: ${JSON.stringify(message)}`);
}
// --- 交互功能 ---
function initChild() {
sendMessage('INIT', { config: 'DarkMode', userId: 'parent-123' });
}
function requestDataFromChild() {
sendMessage('GET_DATA', { key: 'userInfo' });
}
function sendSimpleMessage() {
const input = document.getElementById('messageInput');
if (input.value) {
sendMessage('UPDATE_CONTENT', { text: input.value });
input.value = '';
}
}
// --- 监听来自iframe的消息 ---
window.addEventListener('message', (event) => {
// **安全校验 1: 来源验证 (在生产环境中必须严格检查)**
// if (event.origin !== CHILD_ORIGIN) {
// log(`WARNING: Ignored message from untrusted origin: ${event.origin}`);
// return;
// }
const data = event.data;
log(`RECEIVED: ${JSON.stringify(data)}`);
// **安全校验 2: 检查消息基本结构和序列号**
if (!data || typeof data.sequenceId !== 'number') {
log('WARNING: Ignored message with invalid format.');
return;
}
// **安全校验 3: 防止重放攻击**
if (data.sequenceId <= lastReceivedSequenceId) {
log(`WARNING: Replay attack detected! Received sequenceId: ${data.sequenceId}, last was: ${lastReceivedSequenceId}`);
return;
}
// 验证通过,更新序列号
lastReceivedSequenceId = data.sequenceId;
// --- 根据消息类型处理逻辑 ---
switch (data.type) {
case 'INIT_SUCCESS':
log(`INFO: Child initialization successful with config: ${JSON.stringify(data.payload)}`);
break;
case 'DATA_RESPONSE':
log(`INFO: Received data for key '${data.payload.key}': ${JSON.stringify(data.payload.value)}`);
break;
case 'EVENT_NOTIFY':
log(`INFO: Child notified event '${data.payload.eventName}' with data: ${JSON.stringify(data.payload.details)}`);
break;
default:
log(`WARNING: Received unknown message type: ${data.type}`);
}
});
</script>
</body>
</html>
2. child.html(子页面)
此版本增加了“父页面存在性”检查,并实现了对应的复杂消息处理逻辑。
3. README.md(项目说明)
markdown
# iframe-message-bridge v2
一个用于 iframe 内外网页通信验证的增强版示例项目。
## 功能
- **双向通信**: 父页面和 iframe 子页面之间可以双向发送和接收消息。
- **消息序列号**: 实现了基于序列号的机制,以防止基本的消息重放攻击。
- **复杂消息处理**: 使用了结构化的消息类型 (`INIT`, `GET_DATA`, `EVENT_NOTIFY` 等) 和 `switch` 语句进行逻辑分发,代码更清晰、易于扩展。
- **父页面存在性检查**: 子页面会检查自身是否被嵌入在 iframe 中,如果直接访问,则会显示错误提示。
- **安全基础**: 包含了对消息来源和格式的基本验证框架。
## 使用方法
1. 将 `parent.html` 和 `child.html` 放置在同一目录下。
2. 使用本地服务器(如 `http-server` 或 Python 的 `http.server`)运行项目,确保通过 `http://` 访问。
```bash
# 使用 Python 启动本地服务器
python -m http.server 8000
- 在浏览器中访问
http://localhost:8000/parent.html。
- 你可以:
- 点击 "Initialize Child" 向子页面发送配置信息。
- 点击 "Request User Data from Child" 从子页面获取数据。
- 在输入框中输入文本并点击 "Send Simple Message"。
- 在子页面中点击 "Notify Parent of Click Event" 来向父页面发送事件通知。
- 在浏览器的开发者工具控制台中查看详细的
SENT 和 RECEIVED 日志。
- 尝试直接访问
http://localhost:8000/child.html,你将看到错误提示。
安全注意事项
- 来源验证 (Origin Check): 在生产环境中,必须将代码中的
const ..._ORIGIN = '*'; 替换为具体的目标源(例如 https://example.com),并取消注释相关的 event.origin 检查,这是防止跨站脚本攻击的关键。
- 数据清理 (Data Sanitization): 从另一个窗口接收到的任何数据在用于渲染(例如,通过
innerHTML)或执行操作之前,都应被视为不可信的,并进行适当的清理或验证。
code
### 如何测试新功能
1. **运行项目**:按照 `README.md` 中的说明,在本地服务器上运行并打开 `parent.html`。
2. **测试复杂消息**:点击父页面的 "Initialize Child" 和 "Request User Data from Child" 按钮,观察日志中的 `SENT` 和 `RECEIVED` 消息,以及它们各自的 `type` 和 `payload`。
3. **测试序列号**:在浏览器的开发者工具中,你可以手动尝试重放消息。例如,在父页面的控制台中执行 `iframe.contentWindow.postMessage({type: 'INIT', payload: {}, sequenceId: 1}, '*')` 两次。第二次应该会在子页面的控制台中看到警告。
4. **测试父页面存在性**:直接在浏览器中打开 `child.html` 文件,你会看到 "This page is intended to be used within an iframe" 的错误信息,而不是正常的子页面内容。