Reputation: 1810
Here is my code: I am trying to get the current time of youtube when it runs. However, it always reminds me error messages: "Uncaught TypeError: undefined is not a function". It confuses me a lot. Because I have already defined player ahead. Why the function couldn't be used? Beside getCurrentTime method, I also test other methods, like getVolume(), it also comes across same error.
Any help? Thanks in advance!
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>THis is YOutube API testing </title>
</head>
<body>
<div class="container">
<iframe id="video" width="560" height="315" src="https://www.youtube.com/embed/02GcUZ6hgzo" frameborder="0" allowfullscreen></iframe>
</div>
<script>
//import YouTube API 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);
//create the YouTube Player
var player;
function onYouTubeIframeAPIReady() {
console.log("API is Ready");
player = new YT.Player("video", {
events : {
'onReady': onPlayerReady(),
'onStateChange': onStateChangeEvent()
}
});
}
function onPlayerReady() {
console.log("My plaer is onReady" );
}
function onStateChangeEvent(){
setInterval(function(){
var time = player.getCurrentTime();
//var volume = player.getVolume();
console.log("Get Current Time: " + time);
},1000);
}
</script>
</body>
</html>
Error Message in picture:
Upvotes: 2
Views: 3818
Reputation: 1810
I just figured it out. It is because I didn't enable the javascript in my URL.
Here is the description on Google Official Docs.
Enabling the JavaScript API for a chromeless player
If your application is using a chromeless player, use the following URL to load the player in your application and enable JavaScript API handlers in the player. You can then build your own custom player controls using JavaScript:
http://www.youtube.com/apiplayer?enablejsapi=1&version=3
Enabling the JavaScript API for an embedded player
Use the following URL to load an embedded video player. In the URL, replace the string VIDEO_ID with the 11-character YouTube video ID that identifies the video that the player will show.
http://www.youtube.com/v/VIDEO_ID?version=3&enablejsapi=1
Upvotes: 4