The Youtube Player API's "Ended" state was never triggered

Hey there! I've integrated the Youtube Player API and I'm handling certain actions based on the events triggered. Everything works smoothly when the video is playing or paused, but for some reason, the ended event never gets called. Instead, it triggers the paused event again. I'm fetching the video URL using a GET request from the URL bar, and that part is working perfectly.

<script>
function get(name){
    if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
      return decodeURIComponent(name[1]);
}

//Load player api 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);
var player;

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

function onPlayerReady(evt) {
   // evt.target.playVideo();
}

function onPlayerStateChange(evt) {
    if (evt.data == YT.PlayerState.PLAYING) {
        $.ajax({ url:'insertToDBFromVid.php',
            data: {action : 'playing' },
            type: 'post',
            done: function(result){
                alert(result);
                console.log("Success, Playing");
            },
            error: function(result){
                alert(result)
                console.log("Error in Playing");
            }});

    }

    if (evt.data == YT.PlayerState.ENDED){
        $.ajax({ url:'insertToDBFromVid.php',
            data: {action : 'ended' },
            type: 'post',
            done: function(result){
                alert(result);
                console.log("Success, Ended");
            },
            error: function(result){
                alert(result)
                console.log("Error in Ended");
            }});
    }

    if (evt.data == YT.PlayerState.PAUSED) {
        $.ajax({ url:'insertToDBFromVid.php',
            data: {action : 'paused' },
            type: 'post',
            done: function(result){
                alert(result);
                console.log("Success, Paused");
            },
            error: function(result){
                alert(result)
                console.log("Error in Paused");
            }});
    }

}

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

If anyone has insights on why this issue is occurring, your input would be greatly appreciated :)

Answer №1

I often find myself shouting commands at YouTube's API, and the issue you're facing happens to be one of them :)

According to the YouTube API Docs: https://developers.google.com/youtube/iframe_api_reference#Playback_controls

It's worth noting that the stopVideo function can lead the player into various not-playing states like ended (0), paused (2), video cued (5), or unstarted (-1).

If you call player.stopVideo(), the player's state could transition to any of those mentioned in the quote.

To workaround this issue, avoid using stopVideo() and opt for:

player.seekTo( player.getDuration(), true );
player.playVideo(); //This line can be skipped if the video is already playing

The YouTube player typically sets the state to ENDED once the video naturally finishes. Therefore, the above workaround involves seeking the video to its end before playing it to allow it to end on its own.

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

Loop through items in a list using Angular.js and display each item within an <

I am facing an issue where the model returned from the server contains html tags instead of plain text, such as b tag or i tag. When I use ng-repeat to create a list based on this model, the html is displayed as pure text. Is there a filter or directive av ...

Tips for adjusting the size of various div elements by dragging in Ionic using AngularJS

I am developing an exciting ionic application that is designed to mimic the layout shown in the image below. The app will feature three dynamic div elements that adjust their size based on the movements of a draggable red circle on the screen. Check out t ...

Exploring the Scope of Controllers in AngularJS

Imagine two different sections in an HTML file: <div class="divArea1" ng-controller="myController"> <input ng-click="updateName()" type="button" value="Change Name"/> </div> <div class="divArea1" ng-controller="myController"> ...

What causes the variable "change" to display unexpected results?

Why isn't the function working as expected? I need the change to be 0. I believe there must be a more efficient way to solve this issue, but what's bothering me is that the "change" variable is giving strange values...need help! function checkCa ...

I need to convert the current webpage into a canvas using Javascript in order to manipulate its elements

Is it possible to transform an HTML page into a canvas for graphical manipulation? I am interested in creating a 3D effect that makes the page appear to wrap around the user's head. Do you have any suggestions on how to achieve this? ...

What is the limitation of including a string constant with "</script>" inside a <script> block?

I am genuinely curious about this: I thought that the following code would be valid within an HTML document: <script> var test = "<script>why? </script>"; </script> However, it turns out that this leads to an "unterminated str ...

The challenge of incorporating Laravel, Vue, and JavaScript into a Blade template

It may seem like a silly question, but I am struggling to find a solution. My goal is to load a Vue component and JS file into a blade view. When I include the following: <script src="{{ asset('js/app.js') }}"></script> <script sr ...

Sharing session data between controller and view in an Express.js application

When logging in with the code below in the express controller to redirect to the main page: req.session.user = user.userLogin; if (req.session.user=='Admin') { global.loggedAdmin = user.userLogin; } else { global.loggedUser = user.us ...

Effortlessly generate various socket.io events within a node.js environment

Seeking advice on optimizing and following the DRY principle. My node server is functioning correctly, but I want to streamline the code for future developers. Currently, I have a series of events being set up in this manner: var debug = true; io.sock ...

Tips for creating <table> HTML code without relying on JSF tag libraries like h:datatable or ui:repeat, while still utilizing JSF for managing page navigation

I am facing a challenge with rendering tables in my application. The tables have 12 columns and up to 1800 rows, taking 8 seconds to display using h:dataTable in JSF. I attempted using ui:repeat with a Java List object in JSF for row data retrieval, which ...

Why is the jQuery ajax file uploading feature failing to function properly in the IE9 standard mode?

My file upload function works well in browsers like Chrome and IE10, but encountered an issue when tested on IE9. The Action controller reported that Request.Files were returning files with '0' length. I'm unsure if this problem is related ...

Expanding Perspective in React Native

Having trouble with implementing a camera feature that isn't scaling correctly. The issue seems to be related to the styling of the container View, as when the camera is rendered independently it works fine. The goal is for the camera to activate when ...

Traditional method for comparing prevProps in componentDidUpdate

As I work on prototyping, I've noticed that when new props come in as an array of complex objects, prevProps.myProp===this.props.myProp always returns false. While using JSON.stringify for comparison seems to work, it doesn't feel very reliable. ...

Alter the background color of a div contingent on the checkbox being checked within

I am in search of a solution to modify the background color of a parent div that contains a checkbox. The condition is that the background color should only change when the 'checked' attribute is present within the tag. HTML <div class="comp ...

Guide to transferring the current date to a text box using Angular JS with Protractor

I need to add a date field that is in text type. The HTML code for it is as follows: <input class="form-control ng-pristine ng-invalid ng-touched" type="text" id="date" name="date"> Can anyone assist me in automatically sending the current date to ...

Laravel implementation of Bootstrap Datepicker

Incorporating Laravel bootstrap and a date picker, I have encountered an issue where the todayHighlight feature is not functioning correctly. Additionally, the container aspect is also not working as intended. <link rel="stylesheet" href="https://sta ...

I encountered an issue when trying to include the dotenv file, receiving the following error message: [TypeError: Network request failed]

babel.config.js File plugins: [ ["module:react-native-dotenv", { "envName": "APP_ENV", "moduleName": "@env", "path": ".env", "blocklist": null, "allowlist": null, "blacklist": null, // DEPRECATED "whitelist": ...

Converting dates in JavaScript to the format (d MMMMM yyyy HH:mm am) without using moment.js

Looking to convert the date "2020-02-07T16:13:38.22" to the format "d MMMMM yyyy HH:mm a" without relying on moment.js. Here is one method being utilized: const options = { day: "numeric", month: "long", year: "numeric", } var date1 = new Date ...

Is there a way to prevent special characters from being typed without affecting the arrow keys?

To allow input of numbers from 0 to 9 as well as navigation keys such as up, down, left, right, delete, tab, home, and end, including modifier keys like alt and ctrl, this code is compatible with Chrome and Firefox browsers. $('.commonNumber').k ...

The application ceases to function properly following the update of npm and node on MacOS

I made a huge mistake by updating npm and node versions from 3.10.10 and 6.10.2 to 5.6.0 and 9.3.0, respectively. Now my app is not functioning properly and I am feeling quite desperate. Every time I try to run it, I encounter the following error: /Users ...