html 使用rel=0嵌入YouTube API

8mmmxcuj  于 2023-04-04  发布在  其他
关注(0)|答案(1)|浏览(132)

我知道?rel=0不再删除推荐视频。相反,它只显示来自同一频道的视频。但是我如何将?rel=0附加到嵌入的URL?
我有下面的JS来嵌入视频

(function () {

    var swappers = document.querySelectorAll('[data-video-id]');
    console.log('video')
    swappers.forEach(function (swapper) {
        swapper.addEventListener('click', function (e) {
            e.preventDefault();
            var wrapper = swapper.parentNode;
            var videoId = swapper.dataset.videoId;
            var source = swapper.dataset.videoSource;
            while (wrapper.firstChild) { wrapper.removeChild(wrapper.firstChild); }

            switch (source) {
                case 'youtube':
                    // add youtube api code to do autoplay in safari
                    wrapper.innerHTML = '<div id="video-' + videoId + '"></div>';

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

                    var checkYT = setInterval(function () {
                        if (YT.loaded) {
                            clearInterval(checkYT);
                            var player = new YT.Player('video-' + videoId, {
                                videoId: videoId,
                                events: { 'onReady': function (e) { e.target.playVideo(); } }
                            });
                        }
                    }, 50);
                    break;
                case 'vimeo':
                    // Add Vimeo default Enbed code
                    wrapper.innerHTML = '<iframe src="https://player.vimeo.com/video/' + videoId + '?autoplay=1&title=0&byline=0&portrait=0"width="640" height="360" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen></iframe>';
                    break;
            }

        });
    });

})();

我以为在URL中添加?rel=0会起作用,但由于它是嵌入式的,它只是删除了?rel=0。在URL中添加rel=0不起作用,它最终会显示来自随机频道的视频。
下面是HTML

{% set url = 'https://www.youtube.com/watch?v='~block.video_id~'?rel=0' %}
  <div class="video_wrap">
    <a href="{{ url }}" data-video-id="{{ block.video_id }}" title="Play embedded video" data-video-source="{{ block.video_source ?: "youtube" }}">
    {{ image|raw }}
    </a>
  </div>
f0ofjuux

f0ofjuux1#

在代码的这一部分中:

var checkYT = setInterval(function () {
    [...]
}, 50);

添加带有rel参数和值0playerVars对象:
因此,修改后的代码应该如下所示:

var checkYT = setInterval(function () {
    if (YT.loaded) {
        clearInterval(checkYT);
        var player = new YT.Player('video-' + videoId, {
            videoId: videoId,
            events: { 'onReady': function (e) { e.target.playVideo(); } }, 
            playerVars: { 'rel': 0 }
        });
    }
}, 50);

一旦呈现了iframe,您将看到iframe的URL,并看到rel=0被添加。

相关问题