You have 2 problems with your code:
First you are adding <iframe>
manually and who has to add this is the API
There is a script error, this is a }
at the end:
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onYouTubeIframeAPIReady() {
var player = new YT.Player('player', {
events: {
'onReady': onPlayerReady,
'onPlaybackQualityChange': onPlayerPlaybackQualityChange,
'onStateChange': onPlayerStateChange,
'onError': onPlayerError
}
});
}
function onPlayerReady(event) {
event.target.mute();
}
} <--- AQUI esta sobrando
First change the iframe to:
<div id="player"></div>
And correct the javascript (I've arranged the code indentation for easier reading), since you should add the ID and size in Javascript too:
height: '360',
width: '640',
videoId: 'M7lc1UVf-VE',
Result:
<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);
function onYouTubeIframeAPIReady() {
var player = new YT.Player('player', {
height: '360',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onPlaybackQualityChange': onPlayerPlaybackQualityChange,
'onStateChange': onPlayerStateChange,
'onError': onPlayerError
}
});
}
function onPlayerReady(event) {
event.target.mute();
e.target.playVideo(); //Autoplay se necessário, se não remova esta linha
}
</script>
You can also change the code for this:
<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);
function onYouTubeIframeAPIReady() {
var player = new YT.Player('player', {
events: {
'onReady': function (e) {
e.target.mute();
},
'onPlaybackQualityChange': onPlayerPlaybackQualityChange,
'onStateChange': onPlayerStateChange,
'onError': onPlayerError
}
});
}
</script>
Basic example
See the example working on jsfiddle , follow the code:
<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);
function onYouTubeIframeAPIReady() {
var player = new YT.Player('player', {
height: '360',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': function (e) {
e.target.mute();
e.target.playVideo();
}
}
});
}
</script>
Note: playVideo();
does not work in all environments, as stated in link :
Because of this restriction, functions and parameters such as autoplay, playVideo (), and loadVideoById () will not work in all mobile device environments.