【HTML】iframe跨域访问问题

概述

本地同一浏览器访问本地HTML文件和访问服务器端HTML文件,本地Iframe没有自适应高度,而服务器端的Ifrane自适应了高度。

1.问题重现:

Chrome 版本 41.0.2272.101 (64-bit)

OS:Win8.1

Chrome访问服务器端HTML文件呈现的结果

Chrome访问本地HTML文件呈现的结果

本地访问的HTML文件Iframe没有根据Iframe里面的页面类容自适应高度

2.Iframe自适应高度代码

在index.html文件中间中添加Iframe页面,页面加载时,加载src指定的文件路径

<iframe id="indexFrame" name="index" width="800" onload='iFrameHeight("indexFrame")' src="Web/Index/indexIframe.html"
           frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>

JS脚本自适应调整Iframe高度

    </script>
    <script type="text/javascript" language="javascript">
        function iFrameHeight(id) {
            var ifm = document.getElementById(id);
            var subWeb = document.frames ? document.frames[id].document : ifm.contentDocument;
            if (ifm != null && subWeb != null) {
                ifm.height = subWeb.body.scrollHeight;
            }
        }
    </script>

3.调试代码

Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match.

在这里,我猜测是访问本地文件是file协议(file:///),HTML代码和JS代码存在跨域问题。小弟对file协议不熟悉,请大家不吝赐教。

原文地址:https://www.cnblogs.com/jackson0714/p/4405684.html