Reputation: 51
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:
X-Frame-Options: SAMEORIGIN
or X-Frame-Options: DENY
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:
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
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