• Html cross domain policy造成的iframe自适应高度的解决办法


    今天android加载html的时候遇到无法滚动显示完整内容的问题,确认没有disable scroll方法,经查证是属于iframe设置高度造成的,加载外部html的时候,因为安全策略无法访问到iframe的contentDocument,造成高度不正确。报错:Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with originnull from accessing a frame with origi null

    chrome 会限制protocol,cross domain等等,我遇到的就是local html file 的路径问题,虽然是同一个文件夹里的内容。

    解决方法就是postmessage,利用event来通信传递自身的高度过去。

    这里通配了domain,注意安全性的话,需要post domain and check it at message handler.

    parent :

    <script type="text/javascript">
        // browser compatibility: get method for event 
        // addEventListener(FF, Webkit, Opera, IE9+) and attachEvent(IE5-8)
        var myEventMethod = 
            window.addEventListener ? "addEventListener" : "attachEvent";
        // create event listener
        var myEventListener = window[myEventMethod];
        // browser compatibility: attach event uses onmessage
        var myEventMessage = 
            myEventMethod == "attachEvent" ? "onmessage" : "message";
        // register callback function on incoming message
        myEventListener(myEventMessage, function (e) {
            // we will get a string (better browser support) and validate
            // if it is an int - set the height of the iframe #my-iframe-id
            if (e.data === parseInt(e.data)) 
                document.getElementById('my-iframe-id').height = e.data + "px";
        }, false);
    </script>
    

    child

    <script type="text/javascript">
        // all content including images has been loaded
        window.onload = function() {
            // post our message to the parent
            window.parent.postMessage(
                // get height of the content
                document.body.scrollHeight
                // set target domain
                ,"*"
            )
        };
    </script>
    

      

  • 相关阅读:
    强连通分量 Tarjan
    【二叉搜索树】hdu 3791
    【二叉树】hdu 1622 Trees on the level
    【二叉树】hdu 1710 Binary Tree Traversals
    【leetcode】lower_bound
    【leetcode dp】629. K Inverse Pairs Array
    【leetcode最短路】818. Race Car
    【leetcode 字符串】466. Count The Repetitions
    【leetcode dp】132. Palindrome Partitioning II
    【leetcode dp】Dungeon Game
  • 原文地址:https://www.cnblogs.com/bluelife/p/4136783.html
Copyright © 2020-2023  润新知