xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

How to get the height of a cross-domain iframe page All In One

How to get the height of a cross-domain iframe page All In One

如何获取跨域 iframe 页面高度 All In One

  1. postMessage
// iframe page
function debounce (func, times = 1000) {
    let timer = null;
    return function () {
        if (timer){
            clearTimeout(timer);
        }
        timer = setTimeout(func, times);
    };
};

const sendScrollMessage = () => {
    const app = document.querySelector('#app');
    const height = Math.abs(app.scrollTop);
    parent.postMessage({
        type: 'iframeScroll',
        height: height,
    }, 'https://iframe.xgqfrms.xyz/parent');
};

const app = document.querySelector('#app');
app.addEventListener('scroll', (event) => {
    debounce(sendScrollMessage, 100)();
}, false);

// parent page
const iframe = document.querySelector(`[id="iframe"]`);
// get iframe height ??? postMessage
console.log('iframe', iframe);
iframe.onload = function() {
    let count = 0;
    let timer = setInterval(() => {
        count++;
        if(count > 100) {
            clearInterval(timer);
        }
        console.log('send message to iframe');
        iframe.contentWindow.postMessage({
            type: "iframeScrollEvent",
            other: "other data to pass",
            height: 100,
        }, "*");
    }, 1000);
    console.log('timer', timer);
};

live demo

refs



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2021-12-14 11:52  xgqfrms  阅读(30)  评论(3编辑  收藏  举报