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?
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)
);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With