vue页面监听内嵌的iframe页面点击事件

vue监听iframe点击事件

阅读 13.1k
3 个回答

1.需求: vue项目里有个iframe内嵌页面,现在需要监听内嵌页面点击事件,从而影响到vue文件页面展示情况
2.做法:直接上代码

<body>
   <iframe id="my-iframe" src="./iframe.html" frameborder="0"></iframe>
    <h1>主页</h1>
</body>
<script>
    var iframe = document.getElementById('my-iframe');
    iframe.onload = function() {
        iframe.contentDocument.onclick = function () {
            console.log('点击了iframe页面')
        };
    }
</script>

3.总结:先自己配置个空的环境,便于排查干扰因素
4.没想到sf还有人回答,不错,看来以后可以关注,以后会多提问😄

使用window.postMessage那个东西

<template>
  <iframe ref="ifr"></iframe>
</template>
<script>
export default {
  mounted(){
    console.log(this.$refs.ifr.contentWindow) // 获取iframe里面window对象
    this.$refs.ifr.contentWindow.addEventListener("message",e=>{
      console.log(e) // 跨域的话就要通过postMessage通信
    })
    this.$refs.ifr.contentWindow.addEventListener("click",e=>{
       console.log(e.target) // 不跨越的话就可以操作内部的dom啥的
    })
  }
}
</script>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题