Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an iframe check if itself is in viewport or not?

I'm creating an iframe with a small HTML5 video. the video shouldn't start playing unless the iframe is in the viewport.

I noticed that this isn't as easy as I would like since the iframe is like a sandboxed environment. Is it even possible for an iframe to know if it is in the viewport?

like image 210
ivsterr Avatar asked Dec 13 '25 21:12

ivsterr


1 Answers

Checking whether an element is in the viewport

Here you can find a nice implementation for checking whether an element is in the viewport:

function isInViewport(element) {
    const rect = element.getBoundingClientRect();
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
}

Reaching the parent window

Inside the iframe you can reach the parent window like this:

if (window.parent.isInViewport(document.querySelector('iframe'))) {
    //do something
}

(in the above I'm searching for the first iframe in the parent window for the sake of simplicity, you might need to change your selector)

Yet, modern browsers only allow this kind of communication if the page the iframe points to is of the same domain the main page points to. If the two pages are of different domains, then modern browsers will throw a CORSS error.

You can have a messaging between a main page and the page loaded into the iframe as an alternative, but for that purpose the developers of the main page need to cooperate.

like image 200
Lajos Arpad Avatar answered Dec 16 '25 09:12

Lajos Arpad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!