使用 YouTube 播放器向页面添加视频 API

Add video to page using YouTube Player API

我想使用播放器 API 在单击按钮时加载 YouTube 视频。目标是用户可以输入视频 url,单击一个按钮,然后视频会在下面加载(我排除了下面的表单输入以使其更简单一些)。

我试过使用 location.reload(); 强制重新加载页面,并检查了 some other similar questions 这不是完全有用的,因为他们不使用 API(我需要在以后添加功能时使用)

文档中的

This example 工作正常:

<!DOCTYPE html>
<html>
<body>

<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>

<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('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) {
        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) {
        if (event.data == YT.PlayerState.PLAYING && !done) {
            setTimeout(stopVideo, 6000);
            done = true;
        }
    }
    function stopVideo() {
        player.stopVideo();
    }
</script>
</body>
</html>

我想让这样的东西(非常相似的版本)工作。我不确定为什么目前没有。

<!DOCTYPE html>
<html>
<body>

<input type="submit" value="Submit" id="submit">

<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>

<script>

    document.getElementById("submit").addEventListener("click", function() {

        location.reload();

        // 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) {
            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) {
            if (event.data == YT.PlayerState.PLAYING && !done) {
                setTimeout(stopVideo, 6000);
                done = true;
            }
        }

        function stopVideo() {
            player.stopVideo();
        }

    });

</script>
</body>
</html>

你有两个问题。

1) onYouTubeIframeAPIReady 永远不会被调用,因为它是在 youtube API 加载后定义的。您可以通过添加 console.log.

来查看

2) 重新加载页面时,页面重新加载;即您之前的变量和视频以及所有内容都消失了。

这是一个在点击按钮时加载和播放 YouTube 视频的最小示例:

<input type="submit" value="Submit" id="submit">

<div id="player"></div>

<script src="https://www.youtube.com/iframe_api"></script>
<script>
    document.getElementById('submit').addEventListener('click', () => {
        new YT.Player('player', {
            height: '390',
            width: '640',
            videoId: 'M7lc1UVf-VE',
            events: {
                onReady: e => e.target.playVideo()
            }
        });
    });
</script>

请注意,youtube 代码示例要么试图向后兼容,要么只是没有经过严格更新。他们不遵循现代风格(例如,他们使用 var 而不是 let== 而不是 ===" 而不是 ',等等