Hi I am using youtube iframe embed API. I want to track seek video event by user. Please help me how can I track this.
There is no simple way to track the event with the api alone.
What you could to is running a javascript function in interval and check if the time difference measured is different from the one expecting
Here is an example code :
<html>
    <body>
        <div id="player"></div>
        <script>
            var tag = document.createElement('script');
            tag.src = "https://www.youtube.com/iframe_api";
            var firstScriptTag = document.getElementsByTagName('script')[0];
            firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
            var player;
            function onYouTubeIframeAPIReady() {
                console.log("ready");
                player = new YT.Player('player', {
                    height: '390',
                    width: '640',
                    videoId: 'cRmNPE0HwE8',
                    events: {
                        'onReady': onPlayerReady,
                            'onStateChange': onPlayerStateChange
                    }
                });
                //console.log(player);
            }
            function onPlayerReady(event) {
                event.target.playVideo();
                /// Time tracking starting here
                var lastTime = -1;
                var interval = 1000;
                var checkPlayerTime = function () {
                    if (lastTime != -1) {
                        if(player.getPlayerState() == YT.PlayerState.PLAYING ) {
                            var t = player.getCurrentTime();
                            //console.log(Math.abs(t - lastTime -1));
                            ///expecting 1 second interval , with 500 ms margin
                            if (Math.abs(t - lastTime - 1) > 0.5) {
                                // there was a seek occuring
                                console.log("seek"); /// fire your event here !
                            }
                        }
                    }
                    lastTime = player.getCurrentTime();
                    setTimeout(checkPlayerTime, interval); /// repeat function call in 1 second
                }
                setTimeout(checkPlayerTime, interval); /// initial call delayed 
            }
            function onPlayerStateChange(event) {
            }
        </script>
    </body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With