Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

youtube iframe api parameter rel=0 doesn't work

I need to hide related videos after watching the video. I set rel=0, but it is not working. I am using this page for testing. The rel checkbox value doesn't affect on shown related videos after watching video.

It doesn't work in google chrome. In mozilla firefox it properly works.

like image 600
Viktor Avatar asked Jan 22 '18 16:01

Viktor


2 Answers

Here i found a Solution. stopVideo on player state changed to ENDING

<!DOCTYPE html>
<html>
<head>
    <title>Alternative to hide Related Video & Info</title>
    <script src="https://www.youtube.com/iframe_api"></script>
</head>
<body>

<div id="playerWrapOuter">
    <div id="playerWrap">
        <?php 
            $embed = '<iframe width="560" height="315" src="https://www.youtube.com/embed/HjxYvcdpVnU" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';
            preg_match('/src="(.+?)"/', $embed, $matches);
            $src = $matches[1];
            $params = array(
                'width'          => "640",
                'height'         => "360",
                'enablejsapi'    => 1,
                'rel'            => 0,
                'modestbranding' => 1,
                'showinfo'       => 0,
            );


            $querystring  = http_build_query($params, $src);
            $new_src = $src.'?'. $querystring;
            $embed = str_replace($src, $new_src, $embed);
            $embed = str_replace( '<iframe ', '<iframe ', $embed );

            echo $embed; 
        ?>
    </div>
</div>
<script>
    (function() {
        var player;
        var playerFrame = document.currentScript.previousElementSibling.querySelector("iframe");

        window.onYouTubeIframeAPIReady = function() {
            player = new YT.Player(playerFrame, {
                events: {
                    'onStateChange': onPlayerStateChange
                }
            });
        };
        window.onPlayerStateChange = function(event) {
            if (event.data == YT.PlayerState.ENDED) {
                player.stopVideo();
            }
        };

    })();
</script>
</body>
</html>

Here is a fiddle demo: https://jsfiddle.net/Aishan/znabhuo2/ Hope that helps!!

like image 67
Aishan Avatar answered Oct 04 '22 20:10

Aishan


If you want to hide related video then you should call "player.stopVideo()" when player state is ended "PlayerState.ENDED".

PS: Sorry, english is not my first language.

like image 43
Artur Avatar answered Oct 04 '22 22:10

Artur