window.postMessage安全地实现跨源通信

window.postMessage() 方法可以安全地实现跨源通信。通常,对于两个不同页面的脚本,只有当执行它们的页面位于具有相同的协议(通常为https),端口号(443为https的默认值),以及主机  (两个页面的模数 Document.domain设置为相同的值) 时,这两个脚本才能相互通信。window.postMessage() 方法提供了一种受控机制来规避此限制,只要正确的使用,这种方法就很安全。

从广义上讲,一个窗口可以获得对另一个窗口的引用(比如 targetWindow = window.opener),然后在窗口上调用 targetWindow.postMessage() 方法分发一个  MessageEvent 消息。接收消息的窗口可以根据需要自由处理此事件 (en-US)。传递给 window.postMessage() 的参数(比如 message )将通过消息事件对象暴露给接收消息的窗口

otherWindow.postMessage(message, targetOrigin, [transfer]);

例如:vue项目中,调用iframe子网页中的方法 和在iframe子页面中调用vue父页面中的方法。

父页面代码:

<body>
<h1>我是父页面</h1>
<iframe src="http://127.0.0.1:5050" frameborder="0" style="height: 100%;width: 100%"></iframe>
<script>
function fatherFunction() {
alert('我是父页面中的方法!')
}
window.addEventListener('message', function(e){
console.log(e) //{data:'params'}
fatherFunction()
})
</script>
</body>

子页面代码:

<template>
<div class="weather-app" :class="currentWeatherBG">
<button @click="test">我是子页面按钮,点击调用父页面方法</button>
</div>
</template>
<script>
export default {
methods: {
test() {
window.parent.postMessage({
data :"params"
},'*');
},
}
}
</script>


可以看到,这里关键是子页面通过postMessage方法实现的通信,postMessage的使用方法为:

otherWindow.postMessage(message, targetOrigin, [transfer]);
message为需要传递的信息,
targetOrigin为指定哪些窗口能接收到消息事件,可以为’*’,但是这样很不安全,建议根据实际项目精确匹配。

而父页面则只需要添加事件监听器,在回调中执行需要执行方法或者使用参数。

window.addEventListener('message', function(e){
console.log(e) //{data:'params'}
fatherFunction()
})

posted @ 2021-10-13 17:25  短腿~欧尼  阅读(680)  评论(0编辑  收藏  举报