0

I have an iFrame and I want to execute one of its functions from the parent so I wrote this:

const messenger_iFrame = $(`iframe[src*='url of iframe']`);
messenger_iFrame.attr("id","messengerID"); // adding an ID to the iframe in order to selecting it
document.getElementById('messengerID').contentWindow.iFrameFunc(); // initiate the iframe function

The above code works fine most of the time that's because sometimes when I run the code the iframe doesn't fully load and I get the this is not the function error.

What is your solution?

How can I find out the iframe is loaded and exist in the page before I run this code?

I think maybe we can execute another function from inside the iframe and ...

this code won't work for me because if the iframe is not in the page I can't select it like this... it only works to find out all the elements inside iframe is loaded:

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

Again when there is no iframe in the page yet (because it still has not been loaded) you can not select it like the above code.

foxer
  • 811
  • 1
  • 6
  • 16

1 Answers1

0

Wrap your code in document.addEventListener('DOMContentLoaded', () => { // your code });. This way you can make sure your code is triggered after the page has loaded.

More information: https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event

jasonandmonte
  • 1,869
  • 2
  • 15
  • 24
  • Based on your reference subframes are not loaded yet when this listener executes... so your answer won't work... – foxer May 09 '20 at 17:43