【问题标题】:“catching” errors in embedded youtube videos在嵌入的 youtube 视频中“捕捉”错误
【发布时间】:2021-03-13 01:16:37
【问题描述】:

我在我的网站中嵌入了一个 YouTube 视频,如下所示:

<iframe src="https://www.youtube.com/embed/C_JiP-j2FwM?autoplay=1&loop=1" frameborder="0" allowfullscreen width="100%" height="100%"></iframe>

它运行良好,但在我的工作计算机上,当我使用工作电子邮件登录 Google Chrome 时,我收到以下错误:

发生错误。请稍后再试。 (播放ID:TMjivVwHlyxtQxnL)Learn More

This is expected。这是因为我的工作电子邮件没有访问 YouTube 的权限。这是我尝试使用工作电子邮件访问它时遇到的错误:

根据 DOM Inspector / Network 选项卡对https://www.youtube.com/youtubei/v1/player?key=C_JiP-j2FwM 的请求正在返回此错误:

{
  "error": {
    "code": 403,
    "message": "The caller does not have permission",
    "errors": [
      {
        "message": "The caller does not have permission",
        "domain": "global",
        "reason": "forbidden"
      }
    ],
    "status": "PERMISSION_DENIED"
  }
}

代码可以正常工作,因为我可以在隐身模式中正常播放嵌入的视频(因为在隐身模式下我没有登录工作电子邮件)。

这是完整的代码,因此人们可以重现“问题”并看到它很可能对他们很有用:https://jsfiddle.net/p3jz62uL/

我想做的是“捕捉”错误并在错误发生时更改行为。也许我会一起删除视频,或者我会用图像 idk 替换它。

【问题讨论】:

    标签: javascript youtube youtube-api


    【解决方案1】:

    您可以尝试使用 youtube iframe api 来检测此问题并做出相应响应。查看可用的错误代码https://developers.google.com/youtube/iframe_api_reference#onError 为了让您开始,

    <iframe id="yt-video-iframe" width="630" height="354" src="https://www.youtube.com/embed/C_JiP-j2FwM?autoplay=1&loop=1&enablejsapi=1" frameborder="0" allowfullscreen=""></iframe> <!-- note the &enablejsapi=1 --> 
    
    
    <script type="text/javascript">
      var tag = document.createElement('script');
      tag.src = 'https://www.youtube.com/iframe_api';
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    
        var player;
        // this function will be called automatically !
        function onYouTubeIframeAPIReady() {
                console.log("this func is automatically called");
            player = new YT.Player('yt-video-iframe', {
                events: {
                    'onReady': onPlayerReady,
                    'onStateChange': onPlayerStateChange,
                    'onError': onPlayerError,
                }
            });
        }
        
        function onPlayerReady(event) {
            console.log('video is ready');
        }
    
        function onPlayerStateChange(event) {
            console.log(event.data);
        }
        function onPlayerError(event) {
            console.log(event.data);
        }    
    </script>
    

    由于它是沙盒的,因此我不能将它作为 sn-p 包含在此处,但您可以查看 jsfiddle https://jsfiddle.net/puejzy6o/1/ 示例

    请注意,您的 iframe url 需要查询参数 &enablejsapi=1 并且会自动调用 onYouTubeIframeAPIReady

    注意:我实际上并没有尝试测试您的特定错误是否由 api 处理,但它应该是。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-01
      • 2020-09-10
      • 2014-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 2012-06-25
      相关资源
      最近更新 更多