V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
rogwan
V2EX  ›  问与答

现代浏览器支持的 postMessage in HTML5 的功能,有同学用过吗?

  •  
  •   rogwan · 2017-05-10 12:35:27 +08:00 · 1299 次点击
    这是一个创建于 3063 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我查了 SO 上 votes 有 31 的最高答案,貌似操作了执行不成功( Chrome 和 firefox 下都不行),答案的代码如下:

    If your users are on modern browsers, you can solve this (cross-domain iframe resizer) quite easily with postMessage in HTML5. Here's a quick solution which works well:

    The iframe page:

    <!DOCTYPE html>
    <head>
    </head>
    <body onload="parent.postMessage(document.body.scrollHeight, 'http://target.domain.com');">
      <h3>Got post?</h3>
      <p>Lots of stuff here which will be inside the iframe.</p>
    </body>
    </html>
    

    The parent page which contains the iframe (and would like to know its height):

    <script type="text/javascript">
      function resizeCrossDomainIframe(id, other_domain) {
        var iframe = document.getElementById(id);
        window.addEventListener('message', function(event) {
          if (event.origin !== other_domain) return; // only accept messages from the specified domain
          if (isNaN(event.data)) return; // only accept something which can be parsed as a number
          var height = parseInt(event.data) + 32; // add some extra height to avoid scrollbar
          iframe.height = height + "px";
        }, false);
      }
    </script>
    
    <iframe src='http://example.com/page_containing_iframe.html' id="my_iframe" onload="resizeCrossDomainIframe('my_iframe', 'http://example.com');">
    </iframe>
    
    目前尚无回复
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5441 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 01:35 · PVG 09:35 · LAX 18:35 · JFK 21:35
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.