如何使用iFrame API检测YouTube视频是否已被删除

时间:2017-11-06 01:54:42

标签: javascript iframe youtube youtube-api

是否可以使用iFrame API检测视频是否已被删除或在Youtube上不再可用?

以下代码将检测对youtube iframe的更改,但我可以找到远程关闭的唯一数据点是-3,这意味着未启动,但这也适用于任何工作视频。

CodePen

<iframe id="yt-iframe" width="630" height="354" src="http://www.youtube.com/embed/Rlm8YH2i9gY?enablejsapi=1" frameborder="0" allowfullscreen=""></iframe>

<script type="text/javascript">

    var tag = document.createElement('script');
    tag.id = 'yt-script';
    tag.src = 'https://www.youtube.com/iframe_api';
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    console.log('yt scripts loaded');
    var player;
    function onYouTubeIframeAPIReady() {
        player = new YT.Player('yt-iframe', {
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
    }

    function onPlayerReady(event) {
        console.log('video player ready');
    }

    function onPlayerStateChange(event) {
    console.log(event.data);

    }
</script>

3 个答案:

答案 0 :(得分:1)

设置onError事件处理程序并检查event.data === 100YouTube IFrame Player API描述了所有播放器错误事件。

答案 1 :(得分:0)

您可以在播放视频之前通过检查视频的持续时间进行检测,如果视频的持续时间为0秒,那么很可能会被删除/无法播放

<iframe id="yt-iframe" width="630" height="354" src="http://www.youtube.com/embed/tPEE9ZwTmy0?enablejsapi=1" frameborder="0" allowfullscreen=""></iframe>

<script type="text/javascript">
    var tag = document.createElement('script');
    tag.id = 'yt-script';
    tag.src = 'https://www.youtube.com/iframe_api';
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    console.log('YT scripts loaded');
    var player;
    function onYouTubeIframeAPIReady() {
        player = new YT.Player('yt-iframe', {
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
    }

    function onPlayerReady(event) {
        console.log('Video player ready');
        if (event.target.getDuration() <= 0) {
            console.log('Video likely to be removed');
        }
    }

    function onPlayerStateChange(event) {
        console.log(event.data);
    }
</script>

答案 2 :(得分:0)

不,至少不是直截了当。