Vue中 使用 iframe 嵌入本地 HTML 页面 并 相互通信

2,264 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第6天,点击查看活动详情

1. 使用 iframe 嵌入本地 HTML 页面

在 public 文件夹下新建 static 文件夹,然后将 html 文件及相关引用拷贝到 static 文件夹下。

在这里插入图片描述

<template>
  <div class="wrap">
    <iframe 
      ref="iframe" 
      :src="htmlSrc" 
      width="100%" 
      height="50%" 
      frameborder="0">
    </iframe>
  </div>
</template>

<script>
export default {
  data() {
    return {
      htmlSrc:'static/test.html', // 注意: 直接写 static ,前面不需要加任何路径和字符。
    };
  },
};
</script>

<style lang="scss" scoped>
.wrap{
  width: 100%;
  height: 500px;
}
</style>

2. 相互通信

vue 文件完整代码

<template>
  <div class="wrap">
    <iframe 
      ref="iframe" 
      :src="htmlSrc" 
      width="100%" 
      height="50%" 
      frameborder="0">
    </iframe>
    <button @click="vueSendMsg">vue向iframe传递信息</button>
    <button @click="iframeMethods">触发iframe中的方法</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      htmlSrc:'static/test.html',
    };
  },
  methods: {
    // vue获取iframe传递过来的信息
    getiframeMsg(event){
      const res = event.data;
      console.log(event)
      if(res.cmd == 'myIframe'){
        console.log(res)
      }
    },
    // vue向iframe传递信息
    vueSendMsg(){
      const iframeWindow = this.$refs.iframe.contentWindow;
      iframeWindow.postMessage({ 
        cmd:'myVue',
        params : {
          info: 'Vue向iframe传递的消息',
        } 
      },'*')
    },
    // 触发iframe中的方法
    iframeMethods(){
      this.$refs.iframe.contentWindow.triggerByVue('通过Vue触发iframe中的方法');
    },
  },
  mounted() {
    window.addEventListener('message',this.getiframeMsg)
  },
};
</script>


<style lang="scss" scoped>
.wrap{
  width: 100%;
  height: 500px;
}
</style>

html 文件完整代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <h3>iframe嵌入的页面</h3>
  <button onclick="iframeSendMsg()">iframe向Vue传消息</button>
  
</body>

<script type="text/javascript">
  // iframe向vue传递信息
  function iframeSendMsg(){
    window.parent.postMessage({ 
      cmd:'myIframe',
      params : {
        info: 'iframe向Vue传递的消息',
      } 
    },'*');
  };
  // iframe获取Vue传递过来的信息
  window.addEventListener("message", getVueMsg);
  function getVueMsg(event){
    const res = event.data;
    if(res.cmd == 'myVue'){
      console.log(res)
    }
  };
  function triggerByVue(msg){
    console.log(msg)
  }
</script>
</html>

在这里插入图片描述

  • e.source – 消息源,消息的发送窗口 / iframe;
  • e.origin – 消息源的 URI(可能包含协议、域名和端口),用来验证数据源;
  • e.data – 发送过来的数据;

3. 拓展知识

关于 Window postMessage() 方法

定义和用法:

postMessage() 方法用于安全地实现跨源通信。

语法:

otherWindow.postMessage(message, targetOrigin, [transfer]);
参数说明
otherWindow其他窗口的一个引用,比如 iframe 的 contentWindow 属性、执行 window.open 返回的窗口对象、或者是命名过或数值索引的 window.frames。
message将要发送到其他 window的数据。
targetOrigin指定哪些窗口能接收到消息事件,其值可以是 *(表示无限制)或者一个 URI。
transfer可选,是一串和 message 同时传递的 Transferable 对象。这些对象的所有权将被转移给消息的接收方,而发送一方将不再保有所有权。

关于 Window parent 属性

定义和用法:

parent属性返回当前窗口的父窗口。

语法:

window.parent

传送门:Vue中 iframe 的内容加载慢,实现加载(Loading)效果