一、前言
window.postMessage
是一种运用较多的通信方式,它提供了一种安全的方式来跨源通信。你可以通过这个方法从一个窗口向另一个窗口发送消息,无论这两个窗口是否同源。这个方法接收两个参数:要发送的消息
和一个目标窗口的源
(可以使用通配符 * 来指定允许任何源发送消息)。
window.postMessage 方法接受两个参数:
message:要发送的数据,该数据将通过事件对象的数据属性传递给监听器。
targetOrigin:字符串,指定目标窗口的源(origin),其格式必须是一个 URI(例如 “https://example.com”),或者是一个表示不限制 URL 的特殊值 *
(但是,出于安全考虑,不建议在生产环境中使用 *
)。如果指定的源不匹配接收消息窗口的源,则消息不会被发送;这有助于防止跨站点的消息传递。
二、使用
1. 父组件 ==> 路由是:http://localhost:8080/#/iframe-main
<template>
<div class="iframe-container">
<h3>iframe 通信 => 主页面</h3>
<iframe src="http://localhost:8080/#/iframe-child"
width="100%" height="500px"
frameborder="0"
ref="iframe"
@load="iframeLoaded"
></iframe>
<el-button type="success" @click="sendMessageToChild">发消息给子组件(iframe)</el-button>
</div>
</template>
<script>
export default {
name: 'iframeComponent',
data() {
return {
iframeWin: null,
}
},
mounted() {
window.addEventListener('message'