Vuejs 使用 postmessage 从 iframe 接收事件

Gif*_*ary 6 javascript vue.js

根据此主题从 iframe 调用父窗口函数

假设 iframe 可以将数据发送回父窗口。

现在我使用vuejs实现它,我的代码是

<v-card>
   <iframe :src="url" style="width:100%; height:100vh; border:0px;"></iframe>
</v-card>
Run Code Online (Sandbox Code Playgroud)

在 iframe url 中,我将脚本放入

$('#uploadbtn').bind("click",function(){
     window.parent.postMessage({
       'func': 'parentFunc',
        'message': 'Message text from iframe.'
     }, "*");
});
Run Code Online (Sandbox Code Playgroud)

当用户单击按钮时,它会将消息发送回父级(vue 组件)。

我的问题是如何在 VueJS 端编写代码以从 iframe 获取消息?

谢谢

Phi*_*hil 15

您需要在消息事件上附加一个事件window侦听

例如(在您的组件中)

methods: {
  receiveMessage (event) {
    console.log(event.data)
  }
},
mounted () {
  window.addEventListener('message', this.receiveMessage)
},
beforeDestroy () {
  window.removeEventListener('message', this.receiveMessage)
}
Run Code Online (Sandbox Code Playgroud)

请参阅https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#The_dispatched_event