Mohamed Moustafa
Mohamed Moustafa

Reputation: 509

How to run a function right after contents of an iframe are loaded?

I am currently using :

function printThing(){ 
    let link = parent.document.getElementById("oLink").href; 
    console.log(link); 
}

if (window.attachEvent) {window.attachEvent("onload", printThing);} 
else if (window.addEventListener) {window.addEventListener("load", printThing, false);} 
else {document.addEventListener("load", printThing, false);}

To get a link from the contents of an iframe (which uses srcdoc instead of src) and print it in the console. This code will be added to some stored html before being sent to the frontend.

Is there a way to trigger this once the iframe content is loaded (ie without having to wait for other content in the app)? I tried replacing all the window with document but it doesnt work (it does nothing).

I need to access elements from inside the iframe and change their attributes.

Upvotes: 0

Views: 1211

Answers (1)

user5083456
user5083456

Reputation:

HTML

This method simply uses the onload attribute to invoke the function once the contents of the frame have been loaded.

<iframe id="some_frame" onload="on_iframe_load(this)">
    ....
</iframe>

Obviously, make sure the on_iframe_load(_this) function is in your JS code. To explain further why we pass this into the on_iframe_load(), understand that passing this from a DOM element will pass the reference to the element.

<script>
var on_iframe_load(_this) = () => {
    _this.contentDocument.getElementById("something_in_this_frame").doWhatever(...);
}
</script>

Pure JS

If HTML doesn't float your boat, you can use onload or addEventListener("load", ...) and then access the elements inside the iframe using an element pointer and contentDocument (No IE?)

<script>
document.getElementById("some_frame").onload = function() { // or you could use `addEventListener("load", function(){...})`
    this.contentDocument.getElementById("some_element_in_frame").doThing(...)
}
</script>

Upvotes: 2

Related Questions