vue页面中嵌入iframe外源地址页面 监听iframe 中事件

1.需求 vue中需要嵌入iframe 地址是第三方的 当iframeh中页面点击的时候.vue需要监控到这个事件将本页面关闭.代码中 js 发送和接收方法

//vue组件中是个弹框
<template>
 <el-dialog title="编辑" :visible.sync="editDialog" center :fullscreen="true" append-to-body v-loading="loading">
      <iframe :src="iframeurl" frameborder="0" style="width:100%;" :height="height"></iframe>
 </el-dialog>
</template>

<script>
export default{
data(){
   return{
     iframeurl:"******"  //第三方页面地址
        }
     },
   mounted:{
     //监听iframe变化
        window.addEventListener(message, (eve) => {
        console.log(eve)
       })

   }

 }
</script>


//第三方页面 比如纯html  页面
<!DOCTYPE HTML>
<html>
<head>
    <title>Demo</title>
    <meta charset="utf-8">
    <style>
     
    </style>
</head>
<body>
<button id="btn">向vue组件发送数据</botton>
</body>
</html>
<script>
document.on("click","#btn",function(){
   window.parent.postMessage({  //参数是对象
            cmd: ***,
            params: {
              success: true              
            }
        }, *);
 })


</script>
经验分享 程序员 微信小程序 职场和发展