How to detect if an iframe is cross domain with JavaScript?

Sometimes, we want to detect if an iframe is cross domain with JavaScript.

In this article, we’ll look at how to detect if an iframe is cross domain with JavaScript.

How to detect if an iframe is cross domain with JavaScript?

To detect if an iframe is cross domain with JavaScript, we can check if iframe.contentDocument is defined.

For instance, we write:

<iframe src='https://example.com'>

</iframe>

to add an iframe.

Then we write:

const iframe = document.querySelector('iframe')
const canAccessIframe = (iframe) => {
  try {
    return Boolean(iframe.contentDocument);
  } catch (e) {
    return false;
  }
}
console.log(canAccessIframe(iframe))

to select the iframe with querySelector.

Then we define the canAccessIFrame function that checks if the iframe has the contentDocument property defined.

If it’s defined then it’s not a cross-domain iframe or it’s cross domain and cross domain is allowed.

Otherwise, false is returned.

Conclusion

To detect if an iframe is cross domain with JavaScript, we can check if iframe.contentDocument is defined.