Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
154
rated 0 times [  157] [ 3]  / answers: 1 / hits: 31713  / 10 Years ago, mon, july 7, 2014, 12:00:00

I'm using the iframe YouTube API and I want to track events, for example, sending data to google analytics, when user start and stop video.



<iframe src=https://www.youtube.com/embed/DjB1OvEYMhY></iframe>


I looked https://developers.google.com/youtube/iframe_api_reference?csw=1 and did not find an example how to do that. The example creates iframe and defines onReady and onStateChange as well. How would I do same when I've only iframe on page?


More From » youtube

 Answers
41

This example listens to every play/pause action the user makes, using onPlayerStateChange with its different states, and prints (records) them.



However, you need to create your own record function to do whatever you want with this data.



You also need an ID on your iframe (#player in this case) and to add ?enablejsapi=1 at the end of its URL. And of course, make sure to include the Youtube iframe API.



Note



It's important to declare the API after your code, because it calls onYouTubeIframeAPIReady when it's ready.



<!DOCTYPE html>
<html>
<body>
<iframe id=player src=https://www.youtube.com/embed/DjB1OvEYMhY?enablejsapi=1></iframe>
<h5>Record of user actions:</h5>
<script>
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player( 'player', {
events: { 'onStateChange': onPlayerStateChange }
});
}
function onPlayerStateChange(event) {
switch(event.data) {
case 0:
record('video ended');
break;
case 1:
record('video playing from '+player.getCurrentTime());
break;
case 2:
record('video paused at '+player.getCurrentTime());
}
}
function record(str){
var p = document.createElement(p);
p.appendChild(document.createTextNode(str));
document.body.appendChild(p);
}
</script>
<script src=https://www.youtube.com/iframe_api></script>
</body>
</html>


JS Fiddle Demo


[#70284] Friday, July 4, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
johnnyblaynes

Total Points: 667
Total Questions: 121
Total Answers: 102

Location: Anguilla
Member since Sat, Jan 23, 2021
3 Years ago
;