window.postMessage 在iframe父子页面数据传输

介绍

https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage

window.postMessage

window.postMessage 在iframe父子页面数据传输

 

 

 window.postMessage 在iframe父子页面数据传输

 

 

 

 

发送方

window.postMessage 在iframe父子页面数据传输

 

 

 

接收方

 

window.postMessage 在iframe父子页面数据传输

 

 

 示例:父页面(parentpage_copy.html)传值给子页面(subpage_copy.html)

parentpage_copy

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>父页面</title>
</head>

<body>
  <p>2003年参演中国首部犯罪题材的电视剧《拯救少年犯》 [17] ,该剧由10个故事组成,文章是其中一个故事的男主角。
    2004年参演叶京导演,改编自王朔小说的电视剧《与青春有关的日子》 [18] ,剧中文章饰演卓越一角,开始在影视圈崭露头角 [1] 。
    2005年拍摄第一部古装剧《锦衣卫》,该剧由张黎导演
    电视剧《奋斗》剧照
    电视剧《奋斗》剧照(19张)
  </p>


  <iframe src="http://****/test/iframe/subpage_copy.html" frameborder="0" id="iframe_id" width="100%" scrolling="no"></iframe>
  <script src="jquery-2.1.4.min.js"></script>
  <script>
    var iframe = document.getElementById('iframe_id');
    var iframe_cw = iframe.contentWindow;

    window.onload = function(){
      iframe_cw.postMessage({height:"300px"}, "*"); //通信 * 可以指定域名 
    }
  
  </script>
</body>

</html>

 

子页面(subpage_copy.html)
window.postMessage 在iframe父子页面数据传输
<html data-width="375" data-percent="50" class="iosx1" style="font-size: 50px;">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=0">
  <title>头条巴士</title>
  <style>
    html {
      font-family: PingFangSC-Regular, HelveticaNeue-Thin, "微软雅黑", helvetica, verdana, sans-serif, roboto, NotoSansHand-Regular, "冬青黑体", "华文细黑";
      -ms-text-size-adjust: 100%;
      -webkit-text-size-adjust: 100%;
      height: 100%;
    }

    body {
      margin: auto;
      line-height: 1.5;
      color: #000;
      overflow-x: hidden;
      -webkit-overflow-scrolling: touch;
      height: 100%;
      padding-bottom: constant(safe-area-inset-bottom);
      padding-bottom: env(safe-area-inset-bottom);
    }

    h1,
    h2,
    h3,
    h4,
    h5,
    h6,
    p,
    figure,
    form,
    blockquote {
      margin: 0;
    }

    h1 {
      font-size: 0.44rem;
      color: #393939;
      line-height: 0.62rem;
    }

    .content {
      padding: 0.2rem 0.36rem 0.2rem 0.36rem;
    }

    .content .source {
      font-size: 0.24rem;
      line-height: 0.33rem;
      margin-top: 0.2rem;
      margin-bottom: 0.34rem;
      color: #acacac;
    }

    .content,
    .content p {
      color: #393939;
      font-size: 0.36rem;
      line-height: 0.6rem;
      text-align: justify;
      margin-bottom: 0.4rem;
    }

    .content figure a {
      display: block;
      position: relative;
      background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMAAAAAtCAMAAADP2JRpAAAAM1BMVEXl5eXl5eXl5eXl5eXl5eXl5eXl5eXl5eXl5eXl5eXl5eXl5eXl5eXl5eXl5eXl5eXl5eU6Er+wAAAAEHRSTlMAAQQJEBkkMT9QY3iPqMPghcKzlQAAA19JREFUaN7FmkmigyAMQMMgphSB+5/2L5QZadDWn12R6RnIZAEuCpO7CFp3vvfmcFOOZfMmhVRh+bCX3+VNW/i9915Si5CNNC9D7qOwaQEAuR4YxhPFFHPbo1XRAI5VZNNyvsIQgG3eeyumAJbiSIRWwqFQiHjw6qDNIYAJsu3tNvzWEUB77713bALAwqTG4pvrjRgCnE6oAoBwSf/UDalpAMe+DOBYAJDZKyJuyME0gIYvA7ziHZBucAPDzHJ4HQnCKQAGEdHQAHgCQO+99xv8EuANFAAEAMBZKyQBvfeGXQF4GWPiljZzLvl4jDu5CcDi3tipV/wAAAAgAgAjOtBjhysNIHq29bhMmbM7Jgo/+TWANSiAGgEkP0YBoBtqfxFgS2bhfwEOQ5fcIw2A+U4XHA1z8cR9F4CXA6gAqhxAAEj9vwqg4RqA7gVfIwCWohEKQIqCXGPbiuiIXwRwEUCkmW1jWd+1OTRANqOvxoAWe8WugqkAMrl+SYjlLgEcGmjTJVucnSGArhMaUeUyHwAcq80uEgEUhvNYb0EewwzwvYEPAE43tNEAXj1HTLsDA6sTAHQe49MAsM5lPgDw5tYvdwF0eGZ4EY3SAFhtRMcAup9Q3gIQEaBQAA1AV/n5jBk16UreATDxmS3TARIAh8bNkAGy+UmXOM8VKitiOlnuCcDaL3lwjDbiVwBBySoEpqJ1okU+NuvIYBJAZN1JAL4KnUy7TK6AnwPISYAlBesjAPUYwJKZAQqATo5kAGDhMYDMj5EA7MA5YkcBTwGscDuc5gnAwnMA7+zJLQCdHSH1IID5FoBIcYCFBwFsNj0xoSnzFxdquymWV08C+EmAZqhpTLKF5wHsVwCWXlH0xwC5H7sNYHr1oGcA3nDfjCrZXeUygDKjpN5gk1COAdZPAI5tzeZUVqrdl3WnhVtZA+C4bCNrRyxDIOsigE3wCj4BYMwHZS84on5kogLYsgiwpMWcaNMOJ+AjAIsPdUwRJgCa6E/jzEcpGQGcaPOmLYv5z/wAtnRsAqCO/rQcD7at4cCs2lMCbGx020znwjaxxYQCwHv34p/OH1aFvNhftZmrHpqLTZ0BiAmArE4FVlG/bJSOGLMXYbo1vHbstvZt/onj+IVM/amijsSbLxhloQ7+AOTgG5nWBE8IAAAAAElFTkSuQmCC);
      background-color: hsla(0, 0%, 59%, .1);
      background-repeat: no-repeat;
      background-position: 50%;
      overflow: hidden;
      background-size: 40%;
    }

    .content img {
      width: 100%;
    }

    .content figure a img {
      position: absolute;
      left: 0;
      top: 0;
    }

    .bus_back {
      line-height: .8rem;
      color: #000;
      display: block;
      text-align: right;
      margin: .4rem .4666rem;
      font-size: .36rem;
      color: #ff6060;
    }
  </style>
</head>

<body style="width: 375px;">

  <script>
    !(function (e, t) {
      var n = e.documentElement,
        i = "orientationchange" in window ? "orientationchange" : "resize",
        d = (/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream, function () {
          var t = n.clientWidth;
          t && (t >= 750 ? (t = 750, e.body.style.width = "750px") : e.body.style.width = t + "px", n.style
            .fontSize = 100 * (t / 750) + "px", n.dataset.width = t, n.dataset.percent = 100 * (t / 750))
        });
      d(), e.documentElement.classList.add("iosx" + t.devicePixelRatio), e.addEventListener && t.addEventListener(i,
        d, !1)
    })(document, window)
  </script>
  <div class="content">
    <section class="header">
        <p id="messageHTML"></p>
      <h1>小沈阳老婆经历了啥?如今瘦身成功,长相撞脸韩国女星孔孝真</h1>
      <p class="source">
        2019-10-23 18:00:57 来源:火姿微观
      </p>
    </section>
    <section>
      <p> </p>
      <p> </p>
      <p>沈春阳,她是著名的二人转演员,更是知名艺人小沈阳的妻子。二人转出身的她,在喜剧舞台上游刃有余,同时在演戏方面,也是可以做到得心应手。</p>
      <p>在电视剧樱桃中,沈春阳挑大梁,为众人带来了一部乡村苦情剧。这部电视剧,感动了无数的观众,更是让沈春阳的名字多次被人提起。但后来的沈春阳,就似乎回归家庭了,她很少出现在公众的面前,似乎在专心的照顾家庭。</p>
      <p type="image"> <span> </span></p>
      <figure class="figure-photo-img"><a data-size="640x536"
          data-href="https://ttbs.guangsuss.com/image/bf8ed440e71d2552e0a3d4b4fd8eaf16"
          style="padding-bottom: 83.75%;"><img
            data-original="https://ttbs.guangsuss.com/image/bf8ed440e71d2552e0a3d4b4fd8eaf16"
            src="https://ttbs.guangsuss.com/image/bf8ed440e71d2552e0a3d4b4fd8eaf16" class="lazy"
            data-was-processed="true" style="display: block;"></a></figure>
      <p></p>
      <p></p>
      <p>不过,即便是沈春阳如此低调,网友还是发现了一些不一样的事情。</p>
      <p>有网友就发现,如今的沈春阳,长相大气,更是肤白貌美,还撞脸了韩国的知名演员孔孝真。这样大的变化,也让不少的网友好奇,小沈阳的老婆究竟是经历了什么。</p>
      <p type="image"> <span> </span></p>
      <figure class="figure-photo-img"><a data-size="640x496"
          data-href="https://ttbs.guangsuss.com/image/ab5f54e4e42aa28b291ddb90ed876ec9"
          style="padding-bottom: 77.50%;"><img
            data-original="https://ttbs.guangsuss.com/image/ab5f54e4e42aa28b291ddb90ed876ec9"
            src="https://ttbs.guangsuss.com/image/ab5f54e4e42aa28b291ddb90ed876ec9" class="lazy"
            data-was-processed="true" style="display: block;"></a></figure>
      <p></p>
      <p></p>
      <p>其实,这也未必是沈春阳做什么了!如今的沈春阳,手中有钱,家庭幸福,什么都不愁的她,自然是要有些变化的。更何况,沈春阳的五官还是不错的,也是有点像韩国女星孔孝真的。如今的沈春阳瘦下来之后,会撞脸孔孝真,其实到也正常,不是吗?
      </p>
      <p type="image"> <span> </span></p>
      <figure class="figure-photo-img"><a data-size="640x409"
          data-href="https://ttbs.guangsuss.com/image/3f23683cbfb2bc0e798c69200c658343"
          style="padding-bottom: 63.91%;"><img
            data-original="https://ttbs.guangsuss.com/image/3f23683cbfb2bc0e798c69200c658343" src="/static/img/1.gif"
            class="lazy" data-was-processed="true"></a></figure>
      <p></p>
      <p></p>
      <p>而且,观众对沈春阳的印象,大多都停留在了她所饰演的角色当中。</p>
      <p type="image"> <span> </span></p>
      <figure class="figure-photo-img"><a data-size="339x230"
          data-href="https://ttbs.guangsuss.com/image/fecca0fce8eeeb4f8e9f34bbc5805d45"
          style="padding-bottom: 67.85%;"><img
            data-original="https://ttbs.guangsuss.com/image/fecca0fce8eeeb4f8e9f34bbc5805d45" src="/static/img/1.gif"
            class="lazy" data-was-processed="true"></a></figure>
      <p></p>
      <p></p>
      <p>当年的沈春阳,与小沈阳一起搭档舞台的时候,她穿着土气的毛衣,背着一个奇怪的小包,还剪着一个土土的锅盖头,戴着一个黑框眼镜。这大概是不少人对沈春阳的第一印象,但这样的形象,也让不少的人觉得沈春阳似乎就应该长这样。</p>
      <p type="image"> <span> </span></p>
      <figure class="figure-photo-img"><a data-size="640x492"
          data-href="https://ttbs.guangsuss.com/image/0ee40309dfaf5d5419fbcd560c3eb065"
          style="padding-bottom: 76.88%;"><img
            data-original="https://ttbs.guangsuss.com/image/0ee40309dfaf5d5419fbcd560c3eb065" src="/static/img/1.gif"
            class="lazy" data-was-processed="true"></a></figure>
      <p></p>
      <p></p>
      <p>更不用说,在樱桃中,她又饰演的是一个精神有些问题的农村妇女。所以,在一般人的印象当中,沈春阳似乎就不应该与时尚挂钩。但如今的沈春阳,却用自己的真实样貌告诉观众,自己其实也还是挺漂亮的。</p>
    </section>
    <a class="bus_back" href="/a/1684281751425389876/?qid=z00321">
      <svg t="1561693688103" class="icon" viewBox="0 0 1194 1024" version="1.1" xmlns="//www.w3.org/2000/svg"
        p-id="1183" width="200" height="200" style="
      width: 0.36rem;height: 0.36rem;vertical-align: middle;margin-right: 0.15rem;margin-top: -0.1rem;">
        <path d="M795.497086 512.426311L0 1024V0zM1193.67194 512.426311l-795.497086 511.573689V0z" fill="#ff6060"
          p-id="1184"></path>
      </svg>查看全文</a>

    <section class="bt_no" style="display: none">
      <div id="h5_xuni" class="h5_xuni bt_no" data-loc="h5_xuni" data-id="1568287861bCBpObB6Wp8szzXw5d7a2c75eb107"
        data-ad_type="baidu_ssp" data-strategy_id="1832" data-filter="1832"></div>
    </section>
    <section class="bt_no">
      <div id="h5_fz" class="h5_fz bt_no" data-loc="h5_fz" data-id="1567590343CsSWTNdGv0EU86ve5d6f87c7bc3b2"
        data-ad_type="baidu_ssp" data-strategy_id="2196" data-filter="2196">
        <script type="text/javascript" src="/static/js/clipboard.js"></script>
      </div>
    </section>
    <section class="bt_no">
      <div id="h5_tz" class="h5_tz bt_no" data-loc="h5_tz"></div>
    </section>
  </div>
  <script src="jquery-2.1.4.min.js"></script>
  <script>
    window.addEventListener('message', function (event) {
     document.getElementById('messageHTML').innerText = event.data.height;
      
    }, false);
  </script>
</body>

</html>
View Code

简单介绍主要代码  监听Message

 

 <script>
    window.addEventListener('message', function (event) {
     document.getElementById('messageHTML').innerText = event.data.height;
      
    }, false);

 

在子页面就会看到

window.postMessage 在iframe父子页面数据传输

 

 

 

 

红框上部分为  :父页面内容

红框区域为: 父传字页面值。。。在子页面显示

红框下部分为: 子页面区域

===========================================================================

接下来,,,,

子页面传给父页面值,具体点,把子页面内容在父页面全部展示;让iframe能自适应文章内容

没有传值前,主页面加载iframe内容,未全展示。。。。如下:

 

 

window.postMessage 在iframe父子页面数据传输

 

 

 获取子页面内容区域高度。。。传给父页面。是不是就OK了。。。。。赶紧试一试,不然就忘了。。。人到中年。。。写代码全靠copy

 

子页面代码

<script>

    window.onload = function(){
      var c_h = $(".content").height(); // 获取内容区域高度
      window.parent.postMessage({height:c_h}, 'http://127.0.0.1'); // 可以指定域名
    }
  </script>

 

父页面代码

 <script>
    var iframe = document.getElementById('iframe_id');
    var iframe_cw = iframe.contentWindow;


    window.addEventListener('message', function (event) {
      iframe.style.height = event.data.height + 'px'
    }, false);
  
  </script>

 

传值后:内容全部展示

window.postMessage 在iframe父子页面数据传输

 

==============================================================

接下来,,,串连下。。父传子,子又传父(互相传值)

父页面

<script>
    var iframe = document.getElementById('iframe_id');
    var iframe_cw = iframe.contentWindow;

    //发送消息
    window.onload = function(){
      var message = 'Hello!  The time is: ' + (new Date().getTime());
      iframe_cw.postMessage(message, "*");
    }

    window.addEventListener('message', function (event) {
      console.log('index:  ' + event.data);
      iframe.style.height = event.data.height + 'px'
    }, false);
  </script>

子页面

 <script>
    window.addEventListener('message', function (event) {
      console.log('message lister:  ' + event.data, event);
      var c_h = $(".content").height();
      event.source.postMessage({height:c_h}, event.origin);
    }, false);
  </script>

 

上一篇:javascript-推送事件后serviceWorker的PostMessage


下一篇:猿辅导前端面经