javascript - YouTube 播放器 API 未按文档说明工作
问题描述
YouTube Player API 目前似乎无法正常工作。播放器将正确初始化,但没有任何方法或事件有效。
<div class="flex">
<div id="player"></div>
<div id="log"></div>
</div>
<script>
// for convenience
var isPlayerReady = false;
var logEl = document.getElementById('log');
function addToLog(text) {
logEl.innerHTML = logEl.innerHTML + text + '<br>';
}
window.setTimeout(function () {
if (!isPlayerReady) {
addToLog('5 seconds have passed and the player has not fired the onReady event. This is a good indication that the API is not working properly.');
}
}, 5000);
// from here on, the code is a direct copy of an example from the official docs
// 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() {
addToLog('onYouTubeIframeAPIReady fired, loading Player');
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
isPlayerReady = true;
addToLog('onPlayerReady fired');
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) {
addToLog('onPlayerStateChange fired');
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
我创建了一个简单的 codepen 来监控这里的问题。此示例的大部分内容是官方文档中示例之一的直接副本。
解决方案
[编辑] 从此Google 问题跟踪器中找到了解决方案。好像是浏览器的问题。
试试那些:
- 清除缓存,包括 cookie
- 尝试禁用chrome://flags/#same-site-by-default-cookies并将其放回(对我有用)
希望有帮助
===
你不是一个人!我有使用几天前工作的on...
事件(等)的代码,突然停止工作而没有代码更改。onReady
- 它已发布在 Google 问题跟踪器上(请参见此处)
- 这是另一个stackoverflow帖子,说明了同样的问题
- 它甚至渗透到子库中
react-youtube
(参见问题 #260)
看起来它开始于 9 月 9 日,与 Youtube Data API 版本一致(请参阅9 月 9 日的修订历史)。但我在他们的列表中看不到任何会损害 iframe 事件/功能的内容
这就是我所取得的成就,希望能给某人一个提示,以解决这个问题。♂️ 将在发现时更新此评论。
推荐阅读
- elasticsearch - 带有 XML 文件的 Logstash
- spring-boot - 如何在 Spring Boot / JSP 中显示一组数组?
- dji-sdk - M300 OSDK - 未获得无人机版本
- java - 在 postgres 中使用 hibernate 创建数据库
- ios - 已弃用的 API 使用 - 将不再接受使用 UIWebView 的应用更新
- sql - 从 Big Query 数据集中的所有表中获取特定列数据
- c++ - 使用 decltype 显式实例化函数:适用于 g++ 但不适用于 Visual C++
- clickhouse - 如何以更优化的方式从 LowCardinality(String) 数据类型中获取所有值?
- javascript - 提取由'-'分隔的子字符串
- reactjs - Webpack SplitChunksPlugin 跳过块名称中的数字 - ReactJS