iframe + postMessage 实现跨域通信的相关问题

页面结构

父级页面:a.vue ;    嵌套iframe的URL: http://a/iframe.page.html;

a.vue代码如下:

<template>
    <div>   
        <p>
        这是主界面,嵌套IFrame页面
        </p>  
        <iframe src="http://a/b/iframe.html" id="contentIframe">  </iframe>
     <div>
</template>

父级给子级发消息

在a.vue(父级)中嵌套iframe页时,当父级页面给iframe发送消息时,需要拿到接受消息的iframe的DOM对象,然后再进行消息发送:


// 先拿到iframe的DOM对象,然后再发消息
const val = 'theme1';
const oEl = (document.getElementById('contentIframe')['contentWindow'] as any)
oEl.postMessage({ type: 'CURRENT_SKIN', data:val }, '*');

在iframe链接地址的系统中(嵌套的子系统),对type的事件类型进行监听。代码如下:

window.addEventListener('message', function (event) {
      // console.log('收到当前皮肤::::', event);
      const oState = event.data;
      if (oState.type === 'CURRENT_SKIN') {
        // console.log('收到当前皮肤');
        //   收到信息后,可以操作了。
      }
    });

子级给父级回传消息

子系统给a.vue(父级页面)发消息,也需要找到parent.window,再发消息。代码如下:

window.parent.window.postMessage({type:'FINISH_CURRENT_SKIN',data:true},*)

父级接收消息,代码如下

window.addEventListener('message', function (event) {
      // 监听iframe页是否收到“CURRENT_SKIN”发送的信息,
      // 收到后,关闭“CURRENT_SKIN”的信息发送定时器。
      const oState = event.data;

      if (oState.type === 'FINISH_CURRENT_SKIN') {
          // console.log('收到当前皮肤');
          clearInterval(that.sendCurrentThemeOfTimer);
          that.sendCurrentThemeOfTimer = null;
        }
    });

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Vue中使用iframe + postMessage实现跨域通信,可以参考以下步骤: 1. 在Vue中使用iframe元素来展示需要跨域通信的页面,例如: ```html <template> <div> <iframe ref="iframe" src="https://example.com"></iframe> </div> </template> ``` 2. 在Vue组件的mounted钩子中,注册监听iframe的message事件,接收消息并处理: ```javascript mounted() { window.addEventListener("message", this.handleMessage, false); }, methods: { handleMessage(event) { // 处理接收到的消息 } } ``` 3. 在iframe页面中,使用父窗口的postMessage方法向父窗口发送消息: ```javascript window.parent.postMessage({ data: "hello" }, "*"); ``` 4. 在Vue组件中,使用iframe的contentWindow.postMessage方法向子窗口发送消息: ```javascript this.$refs.iframe.contentWindow.postMessage({ data: "hello" }, "*"); ``` 为了避免iframe卡顿,可以考虑使用懒加载的方式加载iframe元素,即在需要展示iframe的时候再去加载它,而不是在组件被挂载时就加载。可以使用Vue的异步组件来实现懒加载: ```html <template> <div> <component :is="iframeComponent"></component> </div> </template> <script> export default { data() { return { iframeComponent: null } }, mounted() { // 在需要展示iframe的时候加载组件 this.iframeComponent = () => import('./Iframe.vue') } } </script> ``` 在Iframe.vue组件中,再展示实际的iframe元素,并注册message事件监听器。这样可以确保iframe元素只在需要的时候加载,避免卡顿问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值