I'm deploying an application that can be configured to load 3rd-party content in an iframe
. If it's pointed to a service that includes X-Frame-Options: SAMEORIGIN
or similar, the load request can be blocked transparently by the browser. I'd like to improve the user experience when this happens -- display some useful error message on the page, since most users wouldn't know to check the Javascript console to see why it isn't working.
const frame = document.getElementById("frm"),
btn1 = document.getElementById("btn1"),
btn2 = document.getElementById("btn2"),
txt = document.getElementById("txt");
btn1.addEventListener("click", function(){txt.textContent="Loading...";frame.src="https://stackoverflow.com";})
btn2.addEventListener("click", function(){txt.textContent="Loading...";frame.src="https://www.google.com/search?q=hello";})
frame.addEventListener("load", function(evt){txt.innerHTML = txt.innerHTML + "<br/>It loaded!";});
frame.addEventListener("error", function(evt){txt.innerHTML = txt.innerHTML + "<br/>It broke!";});
frame.addEventListener("securitypolicyviolation", function(evt){txt.innerHTML = txt.innerHTML + "<br/>Violation!";});
<iframe id="frm" src="about:blank"></iframe>
<br/>
<button type="button" id="btn1">Load good content</button>
<button type="button" id="btn2">Load bad content</button>
<br/>
<div id="txt"></div>
I have added event listeners to the iframe
element for both load
and error
, but blocked ("bad") requests still fire the load
event and nothing will trigger the error handler. How can I make the "error" handler fire when the request is blocked?
ETA: I also added a listener for securitypolicyviolation
but that doesn't seem to fire either (at least on latest Chromium).