Search code examples
javascriptjqueryiframedocument-ready

Loop through iframes waiting for ready to complete action


I am loading a series of date based URLs into an iframe to extract data from each page using a script on the top frame (same origin).

What is the best/most efficient way to wait until the iframe is ready (and and action performed) before the date loop beings loading the next item into the iframe? (with or without jQuery)

var start = new Date("01/01/2024");
var end = new Date("01/31/2024");
var loop = new Date(start);

while(loop <= end){
    $("#iframe").attr("src", "data.htm?" + loop);
    $("#iframe").ready(function() {
          // Do something in iframe e.g. $("#iframe").contents().find("#export").click()
    });
    
    var newDate = loop.setDate(loop.getDate() + 1);
    loop = new Date(newDate);

}

The loop doesn't seem to wait for the iframe to load before proceeding to the next day. I assume the iframe load/ready functions only attach the functions, but do not prevent the loop loading the next page in the iframe.


Solution

  • Use await and a promise to wait for the next while cycle:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

    
        <script type="module">
        var start = new Date("01/01/2024");
        var end = new Date("01/31/2024");
        var loop = new Date(start);
    
    
        while(loop <= end){
            $("#iframe").attr("src", "data.htm?" + loop);
            await new Promise(resolve => $("#iframe").ready(function() {
                  // Do something in iframe e.g. $("#iframe").contents().find("#export").click()
                  resolve();
            }));
            
            var newDate = loop.setDate(loop.getDate() + 1);
            loop = new Date(newDate);
    
        }
        </script>