YouTube API和跨域请求

ere*_*l55 7 youtube youtube-api

YouTube是否已开始锁定跨源请求?

我在我的网站上使用全屏自动播放英雄视频,它已经运行了很长时间.在过去的几周内它停止工作,我在日志中有以下错误.

无法在'DOMWindow'上执行'postMessage':提供的目标来源(' https://www.youtube.com ')与收件人窗口的来源(' https://tbrogames.github.io ')不匹配.

根据这个问题的答案

我尝试在http和https之间更改主机以查看是否会修复它而它没有.

我的网站抛出错误:https://tbrogames.github.io/

我找到了一个更大的游戏网站也有这个问题. https://playbattlegrounds.com/main.pu

他们还使用youtube视频作为英雄/启动视频; 并且它不再起作用,抛出相同的错误.

相关的JavaScript可以在这里找到 https://github.com/tbrogames/tbrogames.github.io/blob/master/js/defer.js

但是,这工作了很长时间,我没有改变任何代码.这就是为什么我认为这是YouTube所做的改变.

小智 4

我认为这个错误实际上是误导性的。我遇到了同样的问题,但我相信实际上是 chrome 不再自动播放英雄。我收到此错误:Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes

对我来说,修复方法是在播放视频之前用 Javascript对视频调用静音。具有相同属性的嵌入的 iframe 版本不会自动播放

<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('ythero', {
          videoId: '3FjTef9gn3Q',
          height: '100%',
          width: '100%',
          playerVars: {
            rel: 0,
            controls: 0,
            showinfo: 0,
            autoplay: 1,
            loop: 1,
            playlist: '3FjTef9gn3Q',
            modestbranding: 1
          },
          events: {
            'onReady': onPlayerReady,
          }
        });
      }

      // 4. The API will call this function when the video player is ready.
      function onPlayerReady(event) {
        event.target.mute();
        event.target.playVideo();
      }
    </script>
Run Code Online (Sandbox Code Playgroud)