This can be done like the following.
Given a general YouTube embed source code:
<iframe width="560" height="315" src="//www.youtube.com/embed/M7lc1UVf-VE" frameborder="0" allowfullscreen></iframe>
a. Add a enablejsapi
query param and set it to 1 in the src URL
<iframe width="560" height="315" src="//www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1" frameborder="0" allowfullscreen></iframe>
b. Give it a unique id
<iframe id="youtube-video" width="560" height="315" src="//www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1" frameborder="0" allowfullscreen></iframe>
c. Load YouTube iFrame API
<script src="https://www.youtube.com/iframe_api"></script>
d. Create a player that references the existing iFrame
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('youtube-video', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady() {
console.log("hey Im ready");
//do whatever you want here. Like, player.playVideo();
}
function onPlayerStateChange() {
console.log("my state changed");
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…