admin管理员组

文章数量:1318563

I tried to use the YouTube API using an existing iframe on my website.

<iframe id="player" width="560" height="315" src="" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen=""></iframe>

This is the iframe I used. I want to add the autoplay event with js and an event when the video has finished. I DON'T want to create a new iframe because I load the iframes with PHP into my website.

Does anyone know how to bind the youtube API js on existing iframes?

Thx for help :)

I tried to use the YouTube API using an existing iframe on my website.

<iframe id="player" width="560" height="315" src="https://www.youtube./embed/qWv6uI1lTJE" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen=""></iframe>

This is the iframe I used. I want to add the autoplay event with js and an event when the video has finished. I DON'T want to create a new iframe because I load the iframes with PHP into my website.

Does anyone know how to bind the youtube API js on existing iframes?

Thx for help :)

Share Improve this question edited Mar 1, 2018 at 15:36 Nadun Kulatunge 1,7312 gold badges22 silver badges29 bronze badges asked Mar 1, 2018 at 14:56 Cybork HDCybork HD 1211 silver badge5 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

I found another way, where I can use the youtube api how I want:

You have to add "?enablejsapi=1" at the and of the url.

<iframe id="player" width="560" height="315" src="https://www.youtube./embed/qWv6uI1lTJE?enablejsapi=1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

   <script>
var tag = document.createElement('script');

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

//Holds a reference to the YouTube player
var player;

//this function is called by the API
function onYouTubeIframeAPIReady() {
    //creates the player object
    player = new YT.Player('player');

    //subscribe to events
    player.addEventListener("onReady",       "onYouTubePlayerReady");
    player.addEventListener("onStateChange", "onYouTubePlayerStateChange");
}

function onYouTubePlayerReady(event) {
    event.target.playVideo();
}

function onYouTubePlayerStateChange(event) {
    switch (event.data) {
        case YT.PlayerState.ENDED:
            if($('#link-1').length > 0) {
                var href = $('#link-1').attr('href');
                window.location.href = href;
            }
            break;
    }
}

Here is where I found it: https://www.htmlgoodies./beyond/video/respond-to-embedded-youtube-video-events.html

本文标签: javascriptHow to use YouTube API on existing iframeStack Overflow