Youtube embed autoplay on mobile
Asked Answered
O

8

7

I use React to set iframe with youtube video on page in correct size. All works well but for mobiles doesn't work autoplay option.

What is interesting for page, what I have as example video it works perfect.

<iframe type="text/html"  allowTransparency="true"  height="100%" width="100%" preload="metadata" gesture="media" allow="encrypted-media" className="autoplay-iframe"
            src={`https://www.youtube.com/embed/`+this.props.autoplay+`?autoplay=1&version=3&html5=1&hd=1&controls=0&loop=1&playlist=`+this.props.autoplay+`&playsinline=1&rel=0&showinfo=0&modestbranding=1&related=0&enablejsapi=1&origin=`+window.location.hostname} frameborder="0"></iframe>

above is my iframe code. I cut some part of iframe code but there are just style in styles attribute. It isn't important for autoplay. The same finally url for other page works. I'm not sure why. Any hints how I can solve this problem?

Thanks in advance.

Obit answered 23/1, 2018 at 10:25 Comment(0)
M
12

You will not be able to implement this, since it is intentionally disabled to all mobile devices. The reason is for the user to save cellular data. It is also cited in this post.

The reason that video autoplay doesn’t work is simple. The feature is deliberately disabled in both iOS and Android for mobile devices. The reason this is done is to save mobile users money. Such devices (especially mobile phones) often use data connections that charge by bandwidth. They have data limits and going over results in a fee.

This statement was also supported with the following SO post.

Manipur answered 25/1, 2018 at 12:14 Comment(2)
I know this rules but why for example for this one page mattmoran.com.au on the homepage it works as autoplay for mobiles? They also use html5 playerObit
And it is OK to autoplay every single video you scroll through the YouTube app. Bravo Google!Parmer
V
9

I was able to get Youtube videos to play (without muting them). Because loading Youtube videos inline was upsetting Google and their new Core Web Vitals, we implemented a thumbnail placeholder that when clicked (jQuery) initiates loading the video using the Youtube Iframe API. I too could not get them to autoplay at first. The issue was resolved by having the API embed the Iframe--not putting the iframe in place before hand. It autoplays on iOS Safari, Chrome and Firefox. Here's what worked for me:

On document ready:

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

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onYouTubeIframeAPIReady(yt_id, iframe_id, iframe_width, iframe_height){
    player = new YT.Player(iframe_id, {
        width: iframe_width,
        height: iframe_height,
        videoId: yt_id,
        playerVars: { 'autoplay': 1, 'playsinline': 1 },
            events: {
                'onReady': onPlayerReady
            }
    });
}

function onPlayerReady(event) {
    //event.target.mute();
    event.target.setVolume(70);
    event.target.playVideo();
}

on click event:

$('.yt_video_link').on('click', function(e) {
    e.preventDefault();
    var div_id      = $(this).attr('id');
    var div_iframe  = div_id + '_iframe';
    var yt_id       = $('#' + div_id).data('ytid');

    $('#' + div_id + ' .yt_video_play').css('display', 'none');

    onYouTubeIframeAPIReady(yt_id, div_iframe, 560, 315);

});

HTML:

<div id='yt_video_desktop' class='yt_video_link mobile_hide' data-ytid='<?=$yt_id?>'>
    <div id='yt_video_desktop_player' class='yt_video'>
        <img src='/catalog/images/yt_video_thumb_<?=$yt_id?>.jpg' alt='play desktop video' width='768' height='432' id='yt_video_desktop_iframe'>
    </div>
    <div class='yt_video_play'></div>
</div>
Vilmavim answered 14/7, 2021 at 16:6 Comment(0)
T
3

Preview Google official statement "Due to this restriction, functions and parameters such as autoplay, playVideo(), loadVideoById() won't work in all mobile environments.

Reference: https://developers.google.com/youtube/iframe_api_reference

Top answered 19/8, 2020 at 11:55 Comment(0)
B
2

By adding the parameter playsinline: 1 I managed to make the autoplay work on android and ios.

  createYoutubePlayer() {
      this.youtubePlayer = new YT.Player('youtubePlayer', {
      videoId: 'YOURID', // YouTube Video ID
      width: 277,               // Player width (in px)
      height: 600,              // Player height (in px)
      playerVars: {
        autoplay: 1,        // Auto-play the video on load
        controls: 0,        // Show pause/play buttons in player
        showinfo: 1,        // Hide the video title
        modestbranding: 1,  // Hide the Youtube Logo
        loop: 1,            // Run the video in a loop
        fs: 0,              // Hide the full screen button
        cc_load_policy: 0, // Hide closed captions
        iv_load_policy: 3,  // Hide the Video Annotations
        autohide: 1,         // Hide video controls when playing
        playsinline: 1, //forbid fullscreen on ios
      },
      events: {
        onReady: (e) => {
          e.target.mute();
        },
        onStateChange: (e) => {this.onPlayerStateChange(e)}
      }
    });
  }
Bimbo answered 31/10, 2020 at 1:54 Comment(0)
L
2

Youtube video auto play is working here is code

<!-- 1. The <iframe> (video player) will replace this <div> tag. -->
<div class="iframe-container">
  <div id="player"></div>
</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', {
      width: '100%',
      videoId: 'YOUR_VIDEO_ID',
      playerVars: { 'autoplay': 1, 'playsinline': 1 },
      events: {
        'onReady': onPlayerReady
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
     event.target.mute();
    event.target.playVideo();
  }
</script>

<style>
/* Make the youtube video responsive */
  .iframe-container{
    position: relative;
    width: 100%;
    padding-bottom: 56.25%;
    height: 0;
  }
  .iframe-container iframe{
    position: absolute;
    top:0;
    left: 0;
    width: 100%;
    height: 100%;
  }
</style>
Living answered 21/3, 2023 at 16:57 Comment(0)
G
1

The rules have changed so most new mobiles will now let you autoplay, but most video streaming sites like youtube and vimeo haven't enabled the functionality yet. The reason the html5 video worked but the iframe didn't is because youtube disabled it.

Guyer answered 29/3, 2018 at 3:50 Comment(0)
C
1

For anyone dealing with this on react native, you can override the user agent and it works like a charm:

<WebView 
  userAgent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36" 
  ...
Chemo answered 29/12, 2021 at 11:56 Comment(0)
K
0

In Android you can perform autoplay as follows

        val videoIFrame= "<iframe width=\"100%\" height=\"100%\" src=\"https://www.youtube.com/embed/ZJvGITqEbsY?si=2I3KkTgrOEoNtyj_?autoplay=1\" title=\"YouTube video player\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" allowfullscreen></iframe>"

        binding.webView.loadData(videoIFrame,"text/html","utf-8")
        binding.webView.settings.javaScriptEnabled = true
        binding.webView.webChromeClient = object :WebChromeClient(){
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                if(newProgress == 100){
                    implementClickEvent()
                }
            }
        }

Implementation of click event on webview

 private fun implementClickEvent() {
            val x = 250 // X coordinate of the click
            val y = 250 // Y coordinate of the click
    
            val eventDown = MotionEvent.obtain(
                SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
                MotionEvent.ACTION_DOWN, x.toFloat(), y.toFloat(), 0
            )
    
            val eventUp = MotionEvent.obtain(
                SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
                MotionEvent.ACTION_UP, x.toFloat(), y.toFloat(), 0
            )
    
            // Dispatch the events
            binding.webView.dispatchTouchEvent(eventDown)
            binding.webView.dispatchTouchEvent(eventUp)
    
            eventDown.recycle()
            eventUp.recycle()
        }
  • List item
Kishke answered 31/10, 2023 at 6:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.