mangoG
mangoG

Reputation: 51

How to detect if an iframe fails to load due to X-Frame-Options or CSP frame-ancestors restrictions?

I'm trying to detect if an iframe fails to load because the target website has either:

Here's my current code:

<iframe id="myFrame" src="https://example.com"></iframe>
document.getElementById('myFrame').onload = function() {
    console.log('iframe loaded');
};

document.getElementById('myFrame').onerror = function() {
    console.log('iframe failed to load');
};

The iframe can fail to load in these scenarios:

  1. When target site sets X-Frame-Options: SAMEORIGIN or X-Frame-Options: DENY
  2. When target site has CSP header like:
    Content-Security-Policy: frame-ancestors 'none';
    // or
    Content-Security-Policy: frame-ancestors 'self';
    

However, in both cases, the onerror event doesn't fire. I've tried these approaches:

  1. Checking iframe.contentWindow
  2. Using window.addEventListener('error',...)
  3. Monitoring the iframe's readyState
  4. Trying to access iframe.contentDocument (throws security error)

None of these methods reliably detect when the iframe fails to load due to either X-Frame-Options or CSP restrictions.

Is there a reliable way to detect these security-related loading failures? I need to show appropriate fallback content when embedding is prevented.

Expected behavior:

Current behavior:

Upvotes: 4

Views: 73

Answers (1)

David Bradshaw
David Bradshaw

Reputation: 13077

Getting any feedback from the iframe is impossible due to security restrictions in the browser.

An idea you might explore is using the Fetch API in the parent page to inspect the headers on the page you wish to load in the iframe, so you can predict if it will fail.

Upvotes: 0

Related Questions