'Event listener to wait for all XMLHttpRequest inside iframe
I've a simple html page with an iframe
<html>
<head>
$('#page-wrapper').ajaxStop(function() {
console.log("Page Loaded Completely." );
});
</head>
<body>
<h3>Demo page<h3>
<iframe id="page-wrapper" src="#company/profile"></iframe>
</body>
I want to execute a piece of java script after every XMLHttpRequest is complete for the page inside iframe. I've found a way to wait for all ajax requests using ajaxStop but the console message gets printed very early and it doesn't wait for even a single ajax request to finish.
document ready or load also doesn't work here as the page is not responded with a single html file, it is more like a single page application where the dom is available very early followed by request for lot of resource files and some 40-50 number of ajax requests before the page is finally finished.
I am looking for something like Chrome Dev Tools -> Network Tab and type "is:running" in the filters and you will only get the pending requests. Something that can give me the count for the number of active requests.
Solution 1:[1]
In case an update as of year 2020, still have problems with ajaxStop() inside iframe, this method finally did the trick:
$('#my-iframe-id').load(function(){
var instance = this.contentWindow.jQuery,
doc = this.contentWindow.document;
instance(doc).ajaxStart(function(){
console.log('ajaxStart');
});
instance(doc).ajaxStop(function(){
console.log('ajaxStop');
});
instance(doc).ajaxComplete(function(){
console.log('ajaxComplete');
});
});
In this thread use #page-wrapper
as iframe id
Solution 2:[2]
jQuery's ajaxStop
is a global event handler, and should be attached to the document
level.
jQuery's $.ajax
triggers these events internally whenever $.ajax
is used to do an XMLHttpRequest, and the events are bound with on()
so they should bubble, but likely only up to the closest document/window level, which would be the contentWindow of the iframe.
What you need to do is probably something like
$(function() {
$('#page-wrapper').on('load', function() {
var win = iframe.contentWindow || iframe;
var doc = iframe.contentDocument || iframe.contentWindow.document;
$(doc).ajaxStop(function() {
// catch ajax in iframe
});
});
});
This does of course require that the iframe is from the same origin, and is not blocked by the same-origin policy.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jonas Lundman |
Solution 2 | adeneo |