父子页面跨域通信 window.postMessage() / 监听route变化

本文介绍了两种父子页面间的跨域通信方法:1) 使用`window.postMessage()`,详细阐述了发送端和接收端的实现,以及`targetOrigin`参数的使用;2) 监听路由变化,通过改变iframe的URL传递参数,并在子页面中动态响应路由改变。这两种方式在Vue.js和JavaScript应用中尤为实用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方式1 : window.postMessage()

      语法:
        发送端:targetWindow.postMessage(message, targetOrigin, [transfer])

            备注:targetWindow 是接收消息的窗口的引用

                1.1 父端:window.frames +索引值  : 如 window.frames[0]

                1.2 子端:window.parent

                   message 是要具体传的值:例如 { width: 10 }

                   targetOrigin 是指定目标窗口的来源,可以是字符串“*”或URI, *表示任何目标窗口都可接收
 
                   transfer是可选参数
    
        接收端:window.addEventListener("message", receiveMessage, false);

            备注:“message” 是固定的属性,是指要监听消息类型

                  receiveMessage 是方法名,也就是监听到消息后要处理的方法


    例子:

    父parent.html :

  <iframe id="iframeId" name="iframeId" width="100%" src="http://localhost:8080/" frameborder="0" ></iframe>

  <span @click="test" id="test">测试</span>

	mounted () { // 在页面渲染完后进行监听
	    window.addEventListener('message',function(e){
	            console.log(e)
	            document.getElementById('iframeId').style.width = e.data.width
	        },false);
	  },

	  beforeDestroy () { // 在页面销毁前去掉监听,防止内存泄露
	    window.removeEventListener('message')
	  },

	  methods: {
		test(){
		        window.frames[0].postMessage({ hi : 10 },'*') // 给子页面发送信息
		    },
	  }

子child.html :

    <span @click="test" id="test">测试</span>
	
	mounted () { // 监听父页面数据
	    window.addEventListener('message', function(e){
	      console.log(e)
	    })
	  },

	methods: {
		test(){
		        window.parent.postMessage({ width: 100 },'*'); // 给父页面发送信息
		    },
	  }


    方式2: 监听route变化

    父parent.html :通过改变iframe路径,把需要的参数放在url中,再加个时间戳,确保每次点击时url都是改变的

	<iframe id="iframeId" name="iframeId" width="100%" src="http://localhost:8080/"  frameborder="0" ></iframe>

	<a-button type="primary" @click="print">打印</a-button>

	methods: {
		print () {
		        let random = new Date()
      			random = random.getTime() // 时间戳
			 document.getElementById('iframeId').src="http://localhost:8080/#/print?btn_type=print&random="+random
		    },
	  }

子child.html : 通过监听路由的改变,来动态调用子页面中的方法

 watch: {
	    $route: { // 监听路由变化
	      async handler () {
	        let que = this.$route.query
	        await this.initD() // 初始化数据
	        if (que.btn_type == 'print') { // 点击了打印按钮
	          this.$nextTick(() => {
	              this.temPrint(que.btn_type) // 调用打印
           
	          })
	        }
	      },
	      //immediate: true  // 首次进来看需求是否需要监听
	    },
	},

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值