0

I have a case where the backend is sending html to a jsp page containing an iframe. The iframe src is set via an ajax call as shown below :

$(document).ready(function() {
           $.ajax({
                type: "get",
                url: "http://someurl/",
                success: function(msg){ 
                   console.log("Success" + msg);     
                   $('#frameId').attr('src','data:text/html,'+ msg);
                }
            }); 
    });

However the html that is set contains script tag which contains window.onload function as shown below :

<script>
 window.onload = function () {
 //some processing done here
 }

As I understand , this onload wouldn't be called as the iframe src is set by the ajax call whereas the iframe has already loaded. How can this function be invoked ?

skm
  • 426
  • 8
  • 15

2 Answers2

1

It looks like you can trigger onload in an iframe manually once you've set the HTML: https://stackoverflow.com/a/26339638/176615

Matt Andrews
  • 2,868
  • 3
  • 31
  • 53
0

The onload event is fired by the framed document, not the iframe that contains it. So that event on the framed page will fire on its own without you doing anything at all; the framed page doesn't know or care how it was loaded.

Here's what I used to confirm this:

index.html:

<body>
  <iframe id="x"></iframe>
  <script>
    // you can wrap this in a setTimeout too, just to confirm the ajax call doesn't interfere; same result
    document.getElementById('x').setAttribute('src', 'test.html');
  </script>
</body>

test.html:

<body onload="alert('frame onload event fired')">
  framed
</body>
Daniel Beck
  • 20,653
  • 5
  • 38
  • 53