一路繁花似锦绣前程
失败的越多,成功才越有价值

导航

 

1、contentWindow方式通信

  • 声明文件
declare global {
  interface Window {
    childDefineFunction: (message: string) => void
    fatherDefineFunction: (message: string) => void
  }
}

export {}
  • 父窗口
<template>
  <div>
    <button @click="handleClick">父按钮</button>
    <iframe
      style="display: block; width: 100%; height: 600px"
      ref="iframeRef"
      src="/child.html"
      frameborder="0"
    ></iframe>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'

export default defineComponent({
  setup() {
    const iframeRef = ref<HTMLIFrameElement>()

    const handleClick = () => {
      // 需在同一个域
      iframeRef.value?.contentWindow?.childDefineFunction('父向子发送消息')
    }

    window.fatherDefineFunction = (message) => {
      console.log(message)
    }

    return {
      iframeRef,
      handleClick
    }
  }
})
</script>

<style lang="scss" scoped></style>
  • 子窗口
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>子窗口</title>
  <style>
    html, body {
      height: 100%;
    }

    body {
      margin: 0;
      background: #cccccc;
    }
  </style>
</head>
<body>
<button onclick="handleClick()">子按钮</button>
<script>
  window.childDefineFunction = (message) => {
    console.log(message);
  };

  function handleClick() {
    window.parent.fatherDefineFunction("子向父发送消息");
  }
</script>
</body>
</html>

2、postMessage方式通信

  • 父窗口
<template>
  <div>
    <button @click="handleClick">父按钮</button>
    <iframe
      style="display: block; width: 100%; height: 600px"
      ref="iframeRef"
      src="http://localhost:3000"
      frameborder="0"
    ></iframe>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'

export default defineComponent({
  setup() {
    const iframeRef = ref<HTMLIFrameElement>()

    const handleClick = () => {
      // 无需在同一个域
      iframeRef.value?.contentWindow?.postMessage(
        { data: '父向子发送消息' },
        '*'
      )
    }

    window.addEventListener('message', function (event) {
      console.log('父窗口', event)
    })

    return {
      iframeRef,
      handleClick
    }
  }
})
</script>

<style lang="scss" scoped></style>
  • 子窗口
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>子窗口</title>
  <style>
    html, body {
      height: 100%;
    }

    body {
      margin: 0;
      background: #cccccc;
    }
  </style>
</head>
<body>
<button onclick="handleClick()">子按钮</button>
<script>
  window.addEventListener("message", function(event) {
    console.log("子窗口", event);
  });

  function handleClick() {
    window.parent.postMessage({ data: "子向父发送消息" }, "*");
  }
</script>
</body>
</html>
posted on 2023-05-11 14:31  一路繁花似锦绣前程  阅读(285)  评论(0编辑  收藏  举报