以下是基于项目名称 iframe-message-bridge 的示例代码,用于实现 iframe 内外两个网页之间的通信验证。示例代码使用 postMessage API 实现安全的跨域通信,并包含基本的消息验证机制。
项目结构
code
iframe-message-bridge/
├── parent.html # 父页面(包含iframe)
├── child.html # 子页面(iframe内的页面)
└── 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</title>
</head>
<body>
<h1>Parent Page</h1>
<p>Message from iframe: <span id="messageFromIframe">Waiting...</span></p>
<input type="text" id="messageInput" placeholder="Enter message to send to iframe">
<button onclick="sendMessageToIframe()">Send to Iframe</button>
<!-- iframe嵌入子页面 -->
<iframe id="childIframe" src="child.html" style="width: 100%; height: 300px; border: 1px solid #ccc;"></iframe>
<script>
const iframe = document.getElementById('childIframe');
const messageDisplay = document.getElementById('messageFromIframe');
const messageInput = document.getElementById('messageInput');
// 父页面发送消息到iframe
function sendMessageToIframe() {
const message = messageInput.value;
if (message) {
// 使用postMessage发送消息,指定目标源为iframe的contentWindow
iframe.contentWindow.postMessage({
type: 'parentMessage',
content: message,
timestamp: Date.now()
}, '*'); // 注意:在生产环境中,应指定具体的目标源(如 'http://child-domain.com')
messageInput.value = ''; // 清空输入框
}
}
// 监听来自iframe的消息
window.addEventListener('message', (event) => {
// 验证消息来源(在生产环境中应严格检查 event.origin)
if (event.source !== iframe.contentWindow) {
console.warn('Invalid message source!');
return;
}
const data = event.data;
// 验证消息格式
if (data && data.type === 'childMessage') {
messageDisplay.textContent = data.content;
console.log('Received message from iframe:', data);
} else {
console.warn('Invalid message format:', data);
}
});
</script>
</body>
</html>
2. child.html(子页面,iframe内)
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Child Page - iframe-message-bridge</title>
</head>
<body>
<h1>Child Page (Iframe)</h1>
<p>Message from parent: <span id="messageFromParent">Waiting...</span></p>
<input type="text" id="messageInput" placeholder="Enter message to send to parent">
<button onclick="sendMessageToParent()">Send to Parent</button>
<script>
const messageDisplay = document.getElementById('messageFromParent');
const messageInput = document.getElementById('messageInput');
// 子页面发送消息到父页面
function sendMessageToParent() {
const message = messageInput.value;
if (message) {
// 使用postMessage发送消息,目标为父窗口
window.parent.postMessage({
type: 'childMessage',
content: message,
timestamp: Date.now()
}, '*'); // 注意:在生产环境中,应指定具体的目标源(如 'http://parent-domain.com')
messageInput.value = ''; // 清空输入框
}
}
// 监听来自父页面的消息
window.addEventListener('message', (event) => {
// 验证消息来源(在生产环境中应严格检查 event.origin)
if (event.source !== window.parent) {
console.warn('Invalid message source!');
return;
}
const data = event.data;
// 验证消息格式
if (data && data.type === 'parentMessage') {
messageDisplay.textContent = data.content;
console.log('Received message from parent:', data);
} else {
console.warn('Invalid message format:', data);
}
});
</script>
</body>
</html>
3. README.md(项目说明)
markdown
# iframe-message-bridge
一个用于 iframe 内外网页通信验证的示例项目,使用 `postMessage` API 实现安全的跨域通信。
## 功能
- 父页面和 iframe 子页面之间可以双向发送和接收消息。
- 包含基本的消息来源和格式验证。
- 支持跨域通信(需在生产环境中指定具体的目标源)。
## 使用方法
1. 将 `parent.html` 和 `child.html` 放置在同一目录下。
2. 使用本地服务器(如 `http-server` 或 Python 的 `http.server`)运行项目,确保通过 `http://` 访问(直接打开文件可能受限于浏览器安全策略)。
3. 打开 `parent.html`,即可看到父页面和 iframe 子页面之间的通信功能。
## 注意事项
- 在生产环境中,应严格检查 `event.origin` 以确保消息来源的安全性。
- `postMessage` 的目标源参数应指定具体的域名,而不是使用通配符 `*`。
## 示例运行
```bash
# 使用 Python 启动本地服务器
python -m http.server 8000
然后在浏览器中访问 http://localhost:8000/parent.html。
code
### 运行示例
1. 将上述代码保存到对应的文件中。
2. 使用本地服务器运行项目,例如使用 Python 的简单服务器:
```bash
python -m http.server 8000
- 在浏览器中访问
http://localhost:8000/parent.html。
- 你可以在父页面和 iframe 子页面中输入消息并发送,观察消息的传递和显示。
安全注意事项
- 来源验证:在生产环境中,必须严格检查
event.origin 以确保消息来源可信。例如:
javascript
if (event.origin !== 'http://trusted-domain.com') {
console.warn('Invalid origin:', event.origin);
return;
}
- 目标源指定:在
postMessage 中,避免使用通配符 *,应指定具体的目标域名,例如:
javascript
iframe.contentWindow.postMessage(message, 'http://child-domain.com');
扩展功能
如果需要更复杂的功能,可以在消息中添加:
- 消息加密(如使用 AES 加密)。
- 消息序列号(防止重放攻击)。
- 更复杂的消息类型和处理逻辑。
希望这个示例代码对你有帮助!如果需要进一步优化或扩展,请告诉我。