11

When I set the src attribute on an iframe, sometimes an error is logged to the console (seems to be an uncaught exception), and the destination never loads.

For example, if I set myiframe.src = 'http://www.google.com', it just never loads and my Chrome developer tools will log the following message:

Refused to display document because display forbidden by X-Frame-Options.

I understand what this error is, but I want to catch this exception so I can handle it when a website doesn't want to be loaded into an iframe.

Because setting an iframe src is semi-asynchronous, I can't just surround that line with a try catch.

How do I handle iframe errors? iframe.onerror and iframe.onabort don't seem to do the trick either.

Chuck
  • 636
  • 3
  • 8
  • 20
  • Alternatively you could XmlHttpRequest and inject the response into the iframe with document.write.. – smrtl May 03 '13 at 17:17
  • http://stackoverflow.com/questions/6666423/overcoming-display-forbidden-by-x-frame-options this may be help you – Naitik Apr 21 '15 at 07:56
  • so, to add here, iframe doesn't trigger onerror upon having an error, error handling has to be done in an onload handler as per https://javascript.info/onload-onerror#other-resources ` – Gonçalo Vieira Jul 05 '17 at 09:09

1 Answers1

-1

Take a look at:

https://developer.mozilla.org/en/DOM/window.onerror

This is essentially a global, fallback error handler. Google around a bit for more information on how to use this one, but note that there are cross-browser compatibility issues with this approach that you must address, particularly the IE browser family.

This may or may not work well with IFRAME elements, so YMMV.

UPDATE:

Take a look at this question.

How to catch JavaScript errors in all Iframes (with window.error)?

Community
  • 1
  • 1
Lior Cohen
  • 8,985
  • 2
  • 29
  • 27