Determining Autoplay Status Through the YouTube API

After implementing the Youtube API to autoplay a video, I encountered an issue where it only worked on PCs and not on mobile devices. Further investigation revealed that autoplay is disabled on mobile devices.

Now the question arises, is there a way to detect if autoplay is disabled? Or can the video be forced to show the Youtube play button if the video is in state -1?

For example:

if(event.data == -1) {
    // show play button
}

Answer №1

Obtaining this information seems to require testing with a video and confirming if the video's current time has progressed after loading.

This functionality was requested in modernizr, as mentioned in modernizr, but according to Paul Irish's comment, a video is necessary for checking. It appears they are looking to include this in v3 of modernizr.

It is feasible, and the provided pseudocode should help you begin. The first four steps have already been completed, leaving only the last two to be implemented.

create a video element
set video element src to something
add autoplay attribute to it
add element to the dom
bind to that event (something metadata soemthing) that fires when its buffered some
setTimeout after it fires and see if currentTime is > 0

Answer №2

To achieve autoplay functionality without using the arg autoplay, I have provided a solution that has only been tested on PCs. You can experiment with the following code:

VIEW LIVE EXAMPLE

HTML

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

JS

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

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


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

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


    var player;
          function onYouTubeIframeAPIReady() {
            player = new YT.Player('player', {
              height: '390',
              width: '640',
              videoId: 'M7lc1UVf-VE',
              events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
              }
            });
          }


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

          function onPlayerStateChange(event) {
            if (event.data == YT.PlayerState.PLAYING) {

            } else {

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for concealing scrollbars across various browsers without compromising functionality

Is there a way to hide the scrollbar functionality on a horizontal scrollbar without using "overflow: hidden"? I need to maintain JS functionality and ensure compatibility with all modern browsers. $j = jQuery.noConflict(); var $panels = $j('#primar ...

Finding the dimensions of a JSON object and transferring all the information into an array using JavaScript

Fetching data from an API will result in various JSON objects with differing lengths and content, including a mix of objects and arrays that can be nested multiple levels deep. The goal is to extract all data pairs and consolidate them into a single 2D ar ...

Encountered an issue during the iOS build process in Unity within Xcode 7

I'm encountering an issue that is causing a build failure in Xcode after completing the project build in Unity: A fatal error has occurred: lipo: can't write to output file: /Users/applemac/Library/Developer/Xcode/DerivedData/Unity-iPhone-hdkycu ...

Can a <Link> be customized with a specific condition?

On the webpage, there is a list of elements retrieved from a database. When clicking on the last displayed element, I want to link to '/upload' if it shows "Carica Referto", or link to '/consensi/{this.$state.item.hash_consenso}' if it ...

Halting execution: Trying to use the keyword 'import' which is not allowed here

0. April 2023: error cannot be reproduced anymore see here The error is no longer replicable due to bug fixes in react-scripts 5.0.1. 1 Even though the error is gone, the question and my self-answer still seem relevant to Angular users and others as we ...

Enabling withCredentials in Angular 6 for every HttpClient request is crucial for maintaining consistent authentication and

Is there a method to set { withCredentials: true } as the default for every httpclient call, instead of having to add it manually each time? import { HttpClient } from '@angular/common/http'; ... constructor(private httpclient: HttpClient) { } ...

Speedy: Retrieving all route parameters

Currently, I am developing a node.js application with the express framework. Each resource in the app has its own router defined in separate files to keep things organized. Here is an example: app.js var fooRoutes = require('./fooRoutes.js'); . ...

What are the necessary steps for registering Channel and ClientId in the Google Maps SDK for iOS?

I recently wrote some Swift code and now I'm looking to implement durationInTraffic using the Google Maps SDK for iOS. In the documentation, it mentions that Maps for work customers need to include their clientId and channel when registering. However ...

Challenges faced when using jQuery UI autocomplete

My code utilizes jQuery UI's autocomplete method on a text box: $(function() { $('#project').autocomplete({ source: function(request, response){response(Object.getOwnPropertyNames(projects))}, minLength: 0, ...

How can I utilize columns from a junction table in the "where" clause in sequelize?

Looking to execute a Sequelize query on multiple related models: SELECT Cou.country_id, cou.country_name, Sta.state_id, Sta.state_name, Dis.district_id, Dis.district_name, Cit.city_id, Cit.city_name, Loc.location_id, Loc.location_name, Sub_Loc.sub_locatio ...

The expiration time and domain name for cookies are not saved in Angular.js

As a newcomer, I am currently working on storing cookies and setting parameters such as expiration date, domain name, and security. I have created a factory to handle cookie storage. app.factory('SetCookies',function($cookieStore,$timeout,$windo ...

Is it necessary for React to pass onClick as props to sub components?

Attempting to activate an onClick function within a sub-component by including the onClick in the parent component did not yield the desired outcome. // parent component class MainForm extends Component { // code here handleClick = () => { con ...

Is Android Studio Instant Run disabled?

A new feature called Instant Run has been implemented to help decrease the time it takes to run and debug an app. Despite having all the necessary settings configured to enable Instant Run on Android Studio, I am encountering issues with it being enabled. ...

Delete the browsing cache in Internet Explorer from an external source

Currently, I am working on developing an ASP.NET application using Visual Studio. However, a persistent issue I am facing is that every time I launch the application, Internet Explorer caches certain CSS and JS files. This forces me to manually clear the c ...

How can UI events on an Android device be accurately recorded and played back?

Given that the replay takes place on the identical device model, screen orientation, and app UI, we anticipate the events' precise coordinates to remain consistent between recording and replay. Additionally, the device is capable of being rooted. ...

Matching Arrays in Angular Made Easy

Hello friends! I'm seeking assistance since I'm a beginner in the world of Angular and TypeScript. export class TopPage implements OnInit { //city = localStorage.getItem('city'); city = 'bangalore'; areas_array = { ...

Implementing Typescript for managing state in React components

Currently, I have a state set up like this: const [newInvoice, setInvoice] = useState<InvoiceType | null>(invoice) The structure of my InvoiceType is as follows: customer_email: string customer_name: string description: string due_date: stri ...

Tips for addressing flickering issues when scrolling on your device

I am facing an issue with two elements that are set to a fixed position on the page. When these elements reach the bottom of the page, I want them to revert back to a static position using JavaScript. The problem occurs when trying to scroll by clicking a ...

What is causing the discrepancy in results between data.getData() and data.getClipData().getItemAt(i).getUri()?

Currently, I am working on implementing the functionality to select multiple photos from a gallery. I have already successfully implemented the logic for selecting a single photo from the gallery. Uri selectedImage = data.getData(); When debugging, the se ...

Showing additional content in an alternative design

I'm currently facing an issue with the "load more" post button on my Wordpress site. I've designed a unique grid layout for the category page, with a load more button at the bottom. However, when I click the button to load more posts, they appear ...