Search code examples
javascriptjqueryiframeyoutube-iframe-api

Accessing element within iFrame


I need to get the current time of a youtube video I'm playing in an iFrame, but cannot access the video from my script.

I'm able to use console.alert($("#player").children[0].getCurrentTime()) without trouble after selecting the video in the browser dev tools.

However, I get TypeError: Cannot read property 'getCurrentTime' of undefined when that same code is run from the script.

This post on SO made me think it has to do with the element being hidden if dev tools isn't opened. However $("#player").children[0].removeClass("hidden") returns TypeError: $(...).contents is not a function at <anonymous>. The element just doesn't seem to exist.

Below is full code, 90% of which is straight from the first iframe example here.

<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<script>
    // 2. This code loads the IFrame Player API code asynchronously.
    var tag = document.createElement('script');

    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    // 3. This function creates an <iframe> (and YouTube player)
    //    after the API code downloads.
    var player;
    function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
            height: '390',
            width: '640',
            videoId: 'U03lLvhBzOw',
            events: {
                'onReady': onPlayerReady
            }
        });
    }

    // 4. The API will call this function when the video player is ready.
    function onPlayerReady(event) {
        event.target.playVideo();
        console.alert($("#player").children[0].getCurrentTime()) //DOESN'T WORK
    }

</script>
</body>
</html>


Solution

  • You have the var object for the YouTube player already so there's no need to navigate the DOM.

    For example:

    // Play the video
    function onPlayerReady(event) {
        player.playVideo();
        console.log(player.getCurrentTime());
    
        // Jump to 10 seconds
        player.seekTo(10);
    
        // Stop the video after 3 seconds
        setTimeout(stopVideo, 3000);
    }
    
    function stopVideo() {
        console.log(player.getCurrentTime());
        player.stopVideo();
    }