iFrame onload JavaScript event

JavascriptIframeDom EventsOnloadOnload Event

Javascript Problem Overview


I have an iFrame, where I want to send a JavaScript command after loading. My current code looks like this:

<iframe src="http://www.test.tld/" onload="__doPostBack('ctl00$ctl00$bLogout','')">

But with this code the command isn't executed. What must I change to make it work? Only Chrome and Firefox have to be supported.

Javascript Solutions


Solution 1 - Javascript

Use the iFrame's .onload function of JavaScript:

<iframe id="my_iframe" src="http://www.test.tld/">
    <script type="text/javascript">
        document.getElementById('my_iframe').onload = function() {
            __doPostBack('ctl00$ctl00$bLogout','');
        }
    </script>
    <!--OTHER STUFF-->
</iframe>

Solution 2 - Javascript

document.querySelector("iframe").addEventListener( "load", function(e) {

    this.style.backgroundColor = "red";
    alert(this.nodeName);

    console.log(e.target);

} );

<iframe src="example.com" ></iframe>

Solution 3 - Javascript

Your code is correct. Just test to ensure it is being called like:

<script>
function doIt(){
  alert("here i am!");
  __doPostBack('ctl00$ctl00$bLogout','')
}
</script>

<iframe onload="doIt()"></iframe>

Solution 4 - Javascript

Update

As of jQuery 3.0, the new syntax is just .on:

see this answer here and the code:

$('iframe').on('load', function() {
    // do stuff 
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPelekeView Question on Stackoverflow
Solution 1 - JavascriptJasperView Answer on Stackoverflow
Solution 2 - JavascriptanteloveView Answer on Stackoverflow
Solution 3 - Javascripttechnocrusaders.comView Answer on Stackoverflow
Solution 4 - JavascriptScott WardlawView Answer on Stackoverflow