利用window.postMessage()进行跨域的代码
时间: 2023-11-04 09:23:37 浏览: 35
// 父窗口(http://a.com)
window.addEventListener('message', function(event) {
if (event.origin !== 'http://b.com') return; // 只接受来自 http://b.com 的消息
console.log('Received message from http://b.com:', event.data);
}, false);
// 子窗口(http://b.com)
var parentWindow = window.parent;
parentWindow.postMessage('Hello, parent window!', 'http://a.com'); // 发送消息给父窗口
相关问题
window.postMessage实现跨域传参
window.postMessage是一种跨域通信的方法,它可以让不同域名的页面之间进行安全的消息传递。通过该方法,一个页面可以向另一个页面发送消息,而不需要知道对方的具体实现细节。这种方法可以用于实现单点登录、跨域数据共享等功能。但需要注意的是,该方法需要在两个页面之间建立信任关系,否则可能会被恶意利用。
用js写一个window.postMessage实现跨域传参的方法
当使用 `window.postMessage` 方法实现跨域传参时,需要在发送消息的页面和接收消息的页面分别编写代码。以下是一个使用 JavaScript 实现的简单示例:
在发送消息的页面(发送方):
```javascript
// 获取目标窗口对象
const targetWindow = document.getElementById('target-frame').contentWindow;
// 发送消息
targetWindow.postMessage('Hello, receiver!', 'https://example.com');
```
在接收消息的页面(接收方):
```javascript
// 监听 message 事件
window.addEventListener('message', function(event) {
// 验证消息来源,确保只接收来自指定域名的消息
if (event.origin === 'https://example.com') {
// 获取传递的数据
const message = event.data;
// 在控制台打印消息内容
console.log(message);
}
});
```
在发送消息的页面中,首先通过 `document.getElementById` 方法获取目标窗口的引用,然后使用 `postMessage` 方法发送消息。其中,第一个参数是要发送的消息内容,第二个参数是接收方窗口的源(域名),用于验证消息的来源。
在接收消息的页面中,我们通过监听 `message` 事件来接收消息。在事件处理程序中,我们首先验证消息的来源(域名),以确保只接收来自指定域名的消息。然后,我们通过 `event.data` 获取传递的数据,并对其进行处理。
需要注意的是,为了确保安全性,应该始终验证消息的来源,并仅接受来自可信任域名的消息。
希望这个示例对你有所帮助!如有其他问题,请随时提问。