我在将 Youtube iframe API 与最新稳定版 Chrome(85 版)结合使用时遇到问题。我知道一个月前一切正常,但现在,即使完全遵循 Youtube iframe API 文档中的最基本示例:
https://developers.google.com/youtube/iframe_api_reference#Getting_Started
不再工作了。 onReady 和 onStateChange 事件未被触发,并且“播放器”对象缺少其大部分功能,例如 player.playVideo() 未定义。这个问题在我测试过的任何其他浏览器上都没有发生,只有当我在测试这个时登录到我的 Youtube 帐户时才会发生。
我怀疑问题的根源是来自 Youtube 的请求发送的 cookie,因为我在“发现问题”选项卡的控制台中收到此错误:
“通过指定其SameSite属性来指示是否在跨站请求中发送cookie”
,而 Chrome 在 85 版本的注释中提到了这一点:
“拒绝不安全的 SameSite=None cookie”
如果我退出 Youtube,播放器可以正常工作,因为 Youtube 使用这些 cookie 根据您的个人资料推荐不同的视频。
目前我正在寻找解决方法,我唯一能找到的是如果我手动创建 iframe,而不是使用 API,我可以在 src 中放置“youtube-nocookie”而不是“youtube” iframe,但那样我就没有可以引用的对象来控制播放器,例如,如果我必须创建一个自定义按钮来暂停/播放视频。我想主要是在 Youtube 上修复他们的 API,但是现在有什么方法可以解决这个问题吗?
这里有一个 Codepen 来说明这个问题,代码取自上面链接的 Youtube Iframe API 文档:
https://codepen.io/Gabielovv/pen/VwadJvg?editors=1111
// 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: '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) {
console.log("onPlayerReady");
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("onPlayerStateChange");
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
function playYtVideo() {
console.log("playYtVideo");
player.playVideo();
}
最佳答案
从这个 Google Issue Tracker 找到了一个解决方案.看来是浏览器的问题。
试试这些:
- 清除缓存,包括 cookie
- 尝试禁用 chrome://flags/#same-site-by-default-cookies然后放回去(对我有用)
希望对您有所帮助🙃
关于javascript - 使用 Youtube Iframe API 创建的视频播放器停止使用 Chrome v.85,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63894723/