跳转到主要内容

主页内容

跨域情况下实现iframe的高度根据嵌套页面的高度自适应

由 webadmin 发布于 阅读 17 次

问题:a.com下有一个页面,使用iframe包含了b.com下的一个页面test.html,如何让a.com下的页面的iframe高度动态根据test.html页面的高度自适应?

实现步骤:

(1)、允许跨域通信:a.comb.com 需要相互信任并允许跨域通信。这可以通过设置 CORS(跨域资源共享)头或者使用 window.postMessage API 来实现。

(2)、动态调整 iframe 高度:通过 window.postMessagetest.html 页面传递高度信息给 a.com,然后在 a.com 上动态调整 iframe 的高度。

实现代码:

先引入jQuery,本例中使用的是jquery-3.6.0

test.html中:

 <script>
        $(document).ready(function() {
            // 定义一个函数发送高度信息
            function sendHeight() {
                // 获取页面的高度
                var height = $('body').prop('scrollHeight');
                // 通过 postMessage 发送高度信息
                window.parent.postMessage(height, 'https://a.com'); // 目标源应为a.com
            }
            // 页面加载完成后发送一次高度信息
            sendHeight();
            // 监听窗口大小变化事件(可选)
            $(window).resize(sendHeight);
            // 按钮点击事件处理函数
            $('#resizeButton').click(function() {
                // 使用 setTimeout 强制浏览器重新计算布局
                setTimeout(sendHeight, 0);
            });
        });
    </script>

上面代码中:setTimeout(sendHeight, 0); 作用是强制浏览器重新计算布局,在被包含页面的高度会发生改变的时候,可以实时给父页面传递最新的高度数据。例如:test.html中有一些折叠菜单,展开后body的高度增加,折叠后body的高度减小,就可以在展开和折叠的事件中执行setTimeout(sendHeight, 0);来将变化后的高度传给父页面。

a.com下的页面:

 <body>
    <iframe id="myIframe" src="https://b.com/test.html"></iframe>
    <script>
        // 监听来自 iframe 的消息
        window.addEventListener('message', function(event) {
            // 确保消息来源是可信的 b.com
            if (event.origin === 'https://b.com') {
                // 获取高度信息
                var height = event.data;
                // 设置 iframe 的高度
                document.getElementById('myIframe').style.height = height + 'px';
            }
        });
    </script>
</body>