您的位置:首页 > 汽车 > 新车 > vue postMessage 跨域通信

vue postMessage 跨域通信

2024/9/23 13:11:20 来源:https://blog.csdn.net/Ann_52547/article/details/139322257  浏览:    关键词:vue postMessage 跨域通信

一、语法介绍:

1、

otherWindow.postMessage(message, targetOrigin, [transfer])参数介绍otherWindow:其它窗口的引用,比如iframe的contentWindow属性,执行window.open返回的窗口对象,window.open打开过页面获取到的window.opener,或者是命名过或数值索引的window.framesmessage:将要发送到其他 window 的数据,它将会被结构化克隆算法序列化。这意味着你可以不受什么限制的将数据对象安全的传送给目标窗口而无需自己序列化targetOrigin:指定哪些窗口能接收到消息事件,其值可以是 *(表示无限制)或者一个 URI,在发送消息的时候,如果目标窗口的协议、主机地址或端口这三者的任意一项不匹配 targetOrigin 提供的值,那么消息就不会被发送;只有三者完全匹配,消息才会被发送transfer(可选):是一串和 message 同时传递的 Transferable 对象。这些对象的所有权将被转移给消息的接收方,而发送一方将不再保有所有权(一般不会使用)

2、message中的属性有:

data:从其他 window 中传递过来的对象origin:调用 postMessage 时消息发送方窗口的 origin . 这个字符串由 协议、“://“、域名、“ : 端口号”拼接而成,这个 origin 不能保证是该窗口的当前或未来 origin,因为 postMessage 被调用后可能被导航到不同的位置source:对发送消息的窗口对象的引用; 您可以使用此来在具有不同 origin 的两个窗口之间建立双向通信

二、举例

1、postMessage传值

window.postMessage(’token‘, 'http://localhost:8082');
// const domain = window.open('http://localhost:8082/#/progress-bar')  //这行请详见参考链接//可以应用到页面打开iframe
//如果在iframe中传给父窗口则使用如下代码
window.parent.postMessage("UCPSCANRENDER","*"); //"*"可以指定源

注:
window.postMessage(msg, targetOrigin) 和 window.parent.postMessage(msg, “*”) 都是用于在页面间传递消息的方法,但有一些重要区别:

(1)目标窗口:
window.postMessage(msg, targetOrigin): 该方法将消息发送到指定的目标窗口,需要指定目标窗口的源(origin)。
window.parent.postMessage(msg, ""): 该方法将消息发送给父窗口,使用通配符表示允许发送到任何源的窗口。

(2)安全性:
window.postMessage(msg, targetOrigin): 更安全,因为你可以确保消息只发送到你信任的目标窗口。
window.parent.postMessage(msg, “*”): 不够安全,因为它允许将消息发送到任何源的父窗口,可能会被恶意利用。

(3)使用场景:
window.postMessage(msg, targetOrigin): 适用于与特定窗口通信,例如在使用iframe加载的页面之间进行通信。
window.parent.postMessage(msg, “*”): 适用于与父窗口通信,例如在嵌套的iframe中与父页面通信。

2、接收参数

mounted() {// 接收post参数// 在目标窗口中添加 message 事件监听器window.addEventListener('message', this.listenerData);
}beforeDestroy() { //在组件生命周期结束的时候销毁。window.removeEventListener('message', this.listenerData);
},methods: {listenerData(event) {var receivedData = ""let this_ = this;console.log(event)// event 对象包含了传递的消息信息receivedData = event.data; // 接收的消息体  //这里是加密参数var sourceWindow = event.source; // 发送消息的窗口对象var origin = event.origin; // 发送消息的窗口的源地址  console.log("origin", origin)// 在这里可以根据接收到的消息进行相应的处理console.log('Received message:', receivedData);if(receivedData){//对传递的参数进行处理}// 进行响应操作(如果需要的话)var responseData = 'Received your message!';sourceWindow.postMessage(responseData, origin);},
}

参考:
1、vue中通过postMessage传值,通过window.opener双向通信

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com