• 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>
    

      

  • 相关阅读:
    RWCString 定义 memeroy leak
    打开eclipse报错
    Eclipse 增加php插件
    Shell 字符串的截取
    【转载】Shell判断字符串包含关系的几种方法
    Shell $? $* $@ 等含义
    Shell 获取指定行的内容
    概念性进程
    网络编程
    模块详解
  • 原文地址:https://www.cnblogs.com/bluelife/p/4136783.html
Copyright © 2020-2023  润新知