Romel Pérez
Romel Pérez

Reputation: 917

Detect window visibility if inside cross domain iframe

If a web page A is rendered in an <iframe> inside a cross-domain web page B, how to know when A is visible in B?

For example, if web page A is far below in the document scroll of B and the user has to scroll down to see it, how to know when the user has scrolled down enough to see the <iframe>.

enter image description here

There is only control/access to web page A.

Because of Same-Origin Policy, there is no access to events or calculations to get this data.

Page Visibility API only informs when a web page is browser tab active.

Upvotes: 0

Views: 701

Answers (1)

Romel P&#233;rez
Romel P&#233;rez

Reputation: 917

The Intersection Observer API can be used to watch for changes on HTMLElement viewport visibility changes.

To check when the web page visibility, the body element is observed when at least 10% of its content is visible or not.

const options = { threshold: 0.1 };
const callback = ([bodyElement]) => {
  if (bodyElement.isIntersecting) {
    // Element is visible.
  }
};
const observer = new window.IntersectionObserver(callback, options);

const bodyElement = document.querySelector('body');
observer.observe(bodyElement);

Check the specification for more information.

Keep in mind: It is not a standard API. So you might need fallbacks and it is not widely supported. Also, there might be performance concerns.

Upvotes: 2

Related Questions