Jon*_*Jon 3 javascript youtube youtube-api
我刚刚注意到,当我在本地进行测试时,Youtube 事件(onReady、onStateChange)不再触发,但当我将代码上传到JsFiddle时,Youtube 事件(onReady、onStateChange)不再触发。我决定从Youtube Player API复制并粘贴代码,我可以在其中验证它确实无法正常工作。还有其他人有这个问题吗?此问题出现在 Chrome、Firefox、IE、Safari 和 Opera 上。
编辑 - 当我console.log(player);
在本地时,我发现它缺少很多 Youtube 功能,例如seekTo()
, setVolume()
,showVideoInfo()
这些功能存在于 JsFiddle 中。我不确定为什么会发生这种情况,但我相信这可能是我的问题的根源。有任何想法吗?
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '190',
width: '140',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
console.log('ready');
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
console.log('change');
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
Youtube iframe API 目前似乎已损坏,但我还没有看到官方确认。
也可以看看:
\n\n当 iframe 显式写入模板内时,onReady 回调不会触发
\n\n\n\n编辑:这是修复程序:https://code.google.com/p/gdata-issues/issues/detail ?id=5670#c6
\n\n这是上面链接中答案的直接引用:
\n\n\n\n\n快速解决方法是添加 origin= http://www.example.com(将 \n 替换为您的服务器完整域;确保您使用适合您网站的 http:// 或 https://\n )到玩家 iframe 元素的 src= 属性。请确保 origin= 属性的值\n 与主机域和 URL 方案完全匹配。例如
\n
<iframe\n type="text/html"\n width="640"\n height="480"\n src="https://www.youtube.com/embed/VIDEO_ID?enablejsapi=1&origin=https://www.example.com"\n frameborder="0">\n</iframe>\n
Run Code Online (Sandbox Code Playgroud)\n\n\n\n\n我目前正在与工程团队合作,以确定是否需要继续使用 origin=,或者是否可以恢复这个新的要求,但这是立即修复的方法。对于在此期间出现的损坏和缺乏先进的沟通表示歉意。
\n\n如果您使用 YT.Player() 构造函数为您创建 iframe 元素\n,那么这不是问题\xe2\x80\x94,这对于明确包含的开发人员来说是一个边缘情况\n iframe 元素作为页面 HTML 的一部分。
\n
我实施了上面的修复,它对我有用。
\n