个人自学前端43-杂谈-vue中iframe中通信


需求:菜单点击关闭按钮,页面关闭前可能会有页面关闭前事件,需要传方法到页面中

一. 不跨域

外框

<template>
  <div>
    <iframe ref="pageRef" :src="src"></iframe>
  </div>
</template>
<script>
export default {
  data() {
    return {
	  src: '', // 链接
	  ref: '' // 用来获取页面的window对象
	}
  },
  mounted() {
    // 在外框绑定公共事件
    window.$FrameClosePage = (val) => this.closePage(val)
  },
  methods: {
    // 页面关闭前
    beforeClosePage(val) {
	// 获取页面的window对象
	 const curWin = this.$refs.pageRef.contentWindow
	 // 动态ref获取
      // const curWin =
      //   this.$refs[val] &&
      //   this.$refs[val][0] &&
      //   this.$refs[val][0].contentWindow
	// 判断是否跨域
      if (!curWin || curWin.location.host != window.location.host) {
        this.closePage(val)
        return
      }
      // 判断页面是否有关闭前事件
      if (
        curWin.$FrameBeforeClosePage &&
        typeof curWin.$FrameBeforeClosePage === 'function'
      ) {
        // 切换到将要关闭的页面
        this.selectMenu(val)
        // 调用页面关闭前方法
        curWin.$FrameBeforeClosePage((val) => this.closePage(val), val)
      } else {
        // 直接关闭
        this.closePage(val)
      }
	},
    // 外框的公共方法
    closePage(val) {}
  }
}
</script>

工具类 js文件,可放在assets文件夹

// 工具类 js文件,可放在assets文件夹
/**
 * 页面关闭方法
 */
export function $closePage(menuId) {
  const $ = window.$
  const topWindow = $.zoe.getTopParentWindow(window)
  topWindow.$FrameClosePage(menuId)
}

页面

<template>
  <div>
    测试界面1
  </div>
</template>
<script>
// 导入工具类JS文件中的方法
import { $closePage } from "~/assets/core/js/pageUtil";
export default {
  methods: {
    beforePageClose(callback, menuId) {
	  // 方法一 调用公共关闭方法(页面import)
      $closePage(menuId)
	  // 方法二 执行外框传入的关闭方法
        callback(menuId)
	}
  }
}
</script>

二. 跨域

export default {
	methods: {
// 监听跨域页面发过来的消息
    // listenChildMsg() {
    //   window.addEventListener('message', this.doMessageCallback)
    // },
    // // 移除监听message事件
    // removeChildMsg() {
    //   window.removeEventListener('message', this.doMessageCallback)
    // },
    // differentCase(val) {
    //   const curWin =
    //     this.$refs[val] &&
    //     this.$refs[val][0] &&
    //     this.$refs[val][0].contentWindow
    //   if (!curWin) return
    //   const t = { type: 'parentToCloseItemPage', index: val }
    //   curWin.postMessage(t, '*')
    // },
	},
	// beforeDestory() {
  //   this.removeChildMsg() // 移除监听事件
  // },
}
posted @ 2022-04-09 17:06  暗鸦08  阅读(66)  评论(0)    收藏  举报