0

I have a parent that loads a series of children into iframes. I moved all the parent's js into an external js file to clean things up a bit. However, now I'm having trouble connecting to a function in one of the children.

I have an audio tag in the parent that when it completes, needs to check each child to see if it is on screen AND if a custom function is present. However it gives an error that the function is not defined. Here is the sample code from the parent's external js. It doesn't know 'pageThreeCustom' is a function. I'm sure I'm not pathing correctly, I add the document.getElementById to target the iframe ID the child is in with no luck.

var audio = document.getElementById('audio');

audio.addEventListener('ended', function(){
    console.log("audio ended.");

    //ON AUDIO END
    if ($('#a1').isOnScreen()) {
        //example audio swap
        //$(audio).attr('src', "audio/tts/COC_2018_slide1a.mp3");
    }
    else if ($('#a2').isOnScreen()) {
    }
    else if ($('#a3').isOnScreen()) {
        //find page function
        document.getElementById("p3").contentWindow.pageThreeCustom();
    }
layerburn
  • 5
  • 1
  • 2

1 Answers1

0

You can try putting this code snippet in this to check to see if the browser is finding the frame and its contentWindow property:

console.log(document.getElementById('p3').contentWindo‌​w);

You may also want to try using the window object instead of document:

console.log(window.frames.p3);

or just straight to the method call:

window.frames.p3.pageThreeCustom()

A third possibility is that the iframe content isn't yet loaded, what causes the iframe to load? If it happens on page load, you can try waiting until the window onload event is fired before trying to access methods in the frame.

There are a few more possible solutions explained in this issue: Calling javascript function in iframe