iframe内的通信(桥接方法),使用postMessage和使用自定义事件

1、首先看一下我的文档目录
在这里插入图片描述

2、 接下来,上代码

outer.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>外部title>

  <style>
    .outer-wrap {
      display: flex;
      width: 500px;
      height: 500px;
      border: 1px solid;
      margin: auto;
    }

    .outer {
      margin: auto;
    }
  style>
head>

<body>
  <div class="outer-wrap">
    <div class="outer">
      外部
      <iframe id="inlineFrameExample" title="Inline Frame Example" width="300" height="200"
        src="http://127.0.0.1:5500/iframe/inner.html">
      iframe>
    div>
  div>

  <script>
    // 使用postMessage
    window.addEventListener('message', (event) => {
      console.log('Received message is:使用postMessage', event.data);
    }, false);

    // 使用事件
    window.trigger = () => {
      console.log('使用事件')
    }
  script>
body>
html>

inner.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>内部title>

  <style>
    html,body{
      height: 90%;
    }

    .inner-wrap {
      height: 100%;
      display: flex;
      margin: auto;
    }

    .inner {
      width: 100px;
      height: 100px;
      margin: auto;
      text-align: center;
    }
  style>
head>

<body>
  <div class="inner-wrap">
    <div class="inner">
      <button type='button' id="test" onclick="doSomeThing()">内部点击-使用postMessagebutton>
      <button type='button' id="test" onclick="doSomeThingOther()">内部点击-使用事件button>
    div>
  div>

  <script>
    // 使用postMessage
    const doSomeThing = () => {
      const data = {
        isDJ: true,
        isHoliday: false,
      }
      window.parent.postMessage(data, "*");
    }

    // 使用事件
    const doSomeThingOther = () => {
      window.parent.window.trigger();
    }

  script>
body>
html>

补充:
这里的http://127.0.0.1:5500/iframe/inner.html是使用 vscode 插件 Open With Live Server启动的

你可能感兴趣的:(javascript,桥接方法,iframe通信)