Detect Failure to Load Contents of an Iframe

Detecting when Iframe content has loaded (Cross browser)

to detect when the iframe has loaded and its document is ready?

It's ideal if you can get the iframe to tell you itself from a script inside the frame. For example it could call a parent function directly to tell it it's ready. Care is always required with cross-frame code execution as things can happen in an order you don't expect. Another alternative is to set ‘var isready= true;’ in its own scope, and have the parent script sniff for ‘contentWindow.isready’ (and add the onload handler if not).

If for some reason it's not practical to have the iframe document co-operate, you've got the traditional load-race problem, namely that even if the elements are right next to each other:

<img id="x" ... />
<script type="text/javascript">
document.getElementById('x').onload= function() {
...
};
</script>

there is no guarantee that the item won't already have loaded by the time the script executes.

The ways out of load-races are:

  1. on IE, you can use the ‘readyState’ property to see if something's already loaded;

  2. if having the item available only with JavaScript enabled is acceptable, you can create it dynamically, setting the ‘onload’ event function before setting source and appending to the page. In this case it cannot be loaded before the callback is set;

  3. the old-school way of including it in the markup:

    <img onload="callback(this)" ... />

Inline ‘onsomething’ handlers in HTML are almost always the wrong thing and to be avoided, but in this case sometimes it's the least bad option.

Checking if iframe contents are loaded?

To be notified when the iFrame is loaded, you can still use the onload event today.

Create the iFrame and set an ID for JavaScript:

<iframe id="test" src="SRC_URL"></iframe>

Now access the iFrame with JavaScript and set an EventListener for the load event:

const iframe = document.getElementById("test");
iframe.addEventListener("load", function() {
console.log("Finish");
});

When the iFrame has finished loading, "Finish" is logged in the console. I have tested it with Google Chrome and it works fine.

Within the EventHandler you can then perform actions. For example, send a message:

iframe.contentWindow.postMessage({ title: "Hi", message: "Seems to work" }, targetOrigin);

Please also make sure that you have permission to embed the web page (X-frame options).

Catch error if iframe src fails to load . Error :-Refused to display 'http://www.google.co.in/' in a frame..

You wont be able to do this from the client side because of the Same Origin Policy set by the browsers. You wont be able to get much information from the iFrame other than basic properties like its width and height.

Also, google sets in its response header an 'X-Frame-Options' of SAMEORIGIN.

Even if you did an ajax call to google you wont be able to inspect the response because the browser enforcing Same Origin Policy.

So, the only option is to make the request from your server to see if you can display the site in your IFrame.

So, on your server.. your web app would make a request to www.google.com and then inspect the response to see if it has a header argument of X-Frame-Options. If it does exist then you know the IFrame will error.

Javascript: Detect when an iframe is added with src not retrievable

function badIframe(iframe) {
return new Promise(resolve => {
// This uses the new Fetch API to see what happens when the src of the iframe is fetched from the webpage.
// This approach would also work with XHR. It would not be as nice to write, but may be preferred for compatibility reasons.
fetch(iframe.src)
.then(res => {
// the res object represents the response from the server

// res.ok is true if the repose has an "okay status" (200-299)
if (res.ok) {
resolve(false);
} else {
resolve(true);
}

/* Note: it's probably possible for an iframe source to be given a 300s
status which means it'll redirect to a new page, and this may load
property. In this case the script does not work. However, following the
redirects until an eventual ok status or error is reached would be much
more involved than the solution provided here. */
})
.catch(()=> resolve(true));
});
}

new MutationObserver(async records => {
// This callback gets called when any nodes are added/removed from document.body.
// The {childList: true, subtree: true} options are what configures it to be this way.

// This loops through what is passed into the callback and finds any iframes that were added.
for (let record of records) {
for (let node of record.addedNodes) {
if (node.tagName === `IFRAME` && await badIframe(node)) {
// invoke your handler
}
}
}
}).observe(document.body, {childList: true, subtree: true});

How to detect if an iframe is accessible without triggering an error?

If you can add a little JavaScript to all of the pages from your domain you'd like to load in the iframe you could use window.postMessage, which is exempt from the Same Origin Policy. Probably the simplest way would be to have the child window post a message to the parent when it loads and use that instead of onload. For example, you could add this to each page:

if (window.parent) document.addEventListener( 'load', function() {
window.parent.postMessage( "child loaded", "/" );
}, false );

That will post a message to the parent window whenever the page is loaded in a frame with the same origin. You would then listen for it like this:

var iframe = document.getElementById( 'your-iframe' );
var origin = window.location.protocol + '://' + window.location.host;
if (window.location.port != 80) origin += ':' + window.location.port;

window.addEventListener( 'message', function (event) {
if (event.source != iframe.contentWindow
|| event.origin != origin || event.data != "child loaded")
return;

// do here what you used to do on the iframe's load event
}, false );

Note that the examples use the W3C/Netscape event API and thus won't work in Internet Explorer before version 9.

How to detect when an iframe has already been loaded

I've banged my head against a wall until I found out what's happening here.

Background information

  • Using .load() isn't possible if the iframe has already been loaded (event will never fire)
  • Using .ready() on an iframe element isn't supported (reference) and will call the callback immediately even if the iframe isn't loaded yet
  • Using postMessage or a calling a container function on load inside the iframe is only possible when having control over it
  • Using $(window).load() on the container would also wait for other assets to load, like images and other iframes. This is not a solution if you want to wait only for a specific iframe
  • Checking readyState in Chrome for an alredy fired onload event is meaningless, as Chrome initializes every iframe with an "about:blank" empty page. The readyState of this page may be complete, but it's not the readyState of the page you expect (src attribute).

Solution

The following is necessary:

  1. If the iframe is not loaded yet we can observe the .load() event
  2. If the iframe has been loaded already we need to check the readyState
  3. If the readyState is complete, we can normally assume that the iframe has already been loaded. However, because of the above-named behavior of Chrome we furthermore need to check if it's the readyState of an empty page
  4. If so, we need to observe the readyState in an interval to check if the actual document (related to the src attribute) is complete

I've solved this with the following function. It has been (transpiled to ES5) successfully tested in

  • Chrome 49
  • Safari 5
  • Firefox 45
  • IE 8, 9, 10, 11
  • Edge 24
  • iOS 8.0 ("Safari Mobile")
  • Android 4.0 ("Browser")

Function taken from jquery.mark

/**
* Will wait for an iframe to be ready
* for DOM manipulation. Just listening for
* the load event will only work if the iframe
* is not already loaded. If so, it is necessary
* to observe the readyState. The issue here is
* that Chrome will initialize iframes with
* "about:blank" and set its readyState to complete.
* So it is furthermore necessary to check if it's
* the readyState of the target document property.
* Errors that may occur when trying to access the iframe
* (Same-Origin-Policy) will be catched and the error
* function will be called.
* @param {jquery} $i - The jQuery iframe element
* @param {function} successFn - The callback on success. Will
* receive the jQuery contents of the iframe as a parameter
* @param {function} errorFn - The callback on error
*/
var onIframeReady = function($i, successFn, errorFn) {
try {
const iCon = $i.first()[0].contentWindow,
bl = "about:blank",
compl = "complete";
const callCallback = () => {
try {
const $con = $i.contents();
if($con.length === 0) { // https://git.io/vV8yU
throw new Error("iframe inaccessible");
}
successFn($con);
} catch(e) { // accessing contents failed
errorFn();
}
};
const observeOnload = () => {
$i.on("load.jqueryMark", () => {
try {
const src = $i.attr("src").trim(),
href = iCon.location.href;
if(href !== bl || src === bl || src === "") {
$i.off("load.jqueryMark");
callCallback();
}
} catch(e) {
errorFn();
}
});
};
if(iCon.document.readyState === compl) {
const src = $i.attr("src").trim(),
href = iCon.location.href;
if(href === bl && src !== bl && src !== "") {
observeOnload();
} else {
callCallback();
}
} else {
observeOnload();
}
} catch(e) { // accessing contentWindow failed
errorFn();
}
};

Working example

Consisting of two files (index.html and iframe.html):
index.html:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Parent</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
<script>
$(function() {

/**
* Will wait for an iframe to be ready
* for DOM manipulation. Just listening for
* the load event will only work if the iframe
* is not already loaded. If so, it is necessary
* to observe the readyState. The issue here is
* that Chrome will initialize iframes with
* "about:blank" and set its readyState to complete.
* So it is furthermore necessary to check if it's
* the readyState of the target document property.
* Errors that may occur when trying to access the iframe
* (Same-Origin-Policy) will be catched and the error
* function will be called.
* @param {jquery} $i - The jQuery iframe element
* @param {function} successFn - The callback on success. Will
* receive the jQuery contents of the iframe as a parameter
* @param {function} errorFn - The callback on error
*/
var onIframeReady = function($i, successFn, errorFn) {
try {
const iCon = $i.first()[0].contentWindow,
bl = "about:blank",
compl = "complete";
const callCallback = () => {
try {
const $con = $i.contents();
if($con.length === 0) { // https://git.io/vV8yU
throw new Error("iframe inaccessible");
}
successFn($con);
} catch(e) { // accessing contents failed
errorFn();
}
};
const observeOnload = () => {
$i.on("load.jqueryMark", () => {
try {
const src = $i.attr("src").trim(),
href = iCon.location.href;
if(href !== bl || src === bl || src === "") {
$i.off("load.jqueryMark");
callCallback();
}
} catch(e) {
errorFn();
}
});
};
if(iCon.document.readyState === compl) {
const src = $i.attr("src").trim(),
href = iCon.location.href;
if(href === bl && src !== bl && src !== "") {
observeOnload();
} else {
callCallback();
}
} else {
observeOnload();
}
} catch(e) { // accessing contentWindow failed
errorFn();
}
};

var $iframe = $("iframe");
onIframeReady($iframe, function($contents) {
console.log("Ready to got");
console.log($contents.find("*"));
}, function() {
console.log("Can not access iframe");
});
});
</script>
<iframe src="iframe.html"></iframe>
</body>
</html>

iframe.html:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Child</title>
</head>
<body>
<p>Lorem ipsum</p>
</body>
</html>

You can also change the src attribute inside index.html to e.g. "http://example.com/". Just play around with it.



Related Topics



Leave a reply



Submit