How to listen to event search in youtube embed api

Hi, I am using the youtube iframe API. I want to track the search for a video event by a user. Please help me how can I track this.

+9
source share
2 answers

There is no easy way to track an event using api only.

That you can use the javascript function in the interval and check if the time difference is different from the expected

Here is a sample 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> 
+12
source

You can do this a little simply (without timers):

 <script> const tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api"; const firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); let previousAction; let previousTime; function onYouTubeIframeAPIReady() { player = new YT.Player('player', { events: { 'onStateChange': onPlayerStateChange } }); } function onPlayerStateChange({target, data}) { if(data != 3) { // we don't need to detect buffering return; } const currentTime = target.getCurrentTime(); // detect existing action and previous action which is not paused if (!previousAction || previousAction != 2 ) { // return existing youtube api data (-1 || 0 || 1 || 5 ) return data; } else if (Math.abs(previousTime - currentTime) > 1 ) { // we have Seek event and we have time when it was started(previousTime). Also we have finish time of Seek event(currentTime). return 'Seek' } previousTime = currentTime; previousAction = data } </script> 
0
source

Source: https://habr.com/ru/post/984302/


All Articles