サンプルコード:
<div id="ytplayer"></div>
<a id="start" href="#">start</a>
<script>
// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('ytplayer', {
height: '390',
width: '640',
videoId: 'U6oKcAXiVlo',
playerVars: { 'autoplay': 0, 'controls': 0, 'showinfo': 0 },
});
}
document.getElementById("start").addEventListener("click", function () {
player.playVideo();
});
</script>
再現可能なテストケース: http://fiddle.jshell.net/3fpusLm5/show/
プレーヤー変数はスコープ内にあります。ただし、オブジェクトで使用できるはずのメソッド (playVideo、pauseVideo など) の呼び出しは機能しません。それは言いObject does not support this property or method
ます。
このコードは、ほとんどの最新のブラウザーで機能します。プレーヤーはすでにロードされていると確信しています。onReady コールバックをテストし、30 秒待ってみました。