E
E
Evgeny Zhurov2018-02-24 11:25:44
YouTube
Evgeny Zhurov, 2018-02-24 11:25:44

How to properly upload a video using the YouTube API?

Good afternoon. Faced a set of problems accompanying the YouTube API. First of all, the task is to connect this very API by clicking on a third-party button and start the video. Those. The API cannot be directly connected when the page is loaded. I did everything according to the documentation .
I do the following:

$(document).on('click', "#playVideo", function() {
                // Ссылка на ролик зашита в атрибут data-link кнопки
    videoLink = $(this).attr("data-link").split("v=")[1] || $(this).attr("data-link").split("embed/")[1];
    // Вызываем функцию, подключающую API
    getYouTubeAPI(onYouTubeIframeAPIReady);
});

Here is the function that connects the API:
function getYouTubeAPI(callback) {
  var doc = document,
    script = doc.createElement('script'),
    lastScript = $("script")[$("script").length - 1];

  script.src = 'https://www.youtube.com/iframe_api';
  lastScript.before(script);
        // В конце вызываем функцию, которая создает объект плеера и запускает видео
  callback();
}

A function that creates a player object and starts the video:
var videoLink,
      player;

function onYouTubeIframeAPIReady() {
  player = new YT.Player('videoInner', {
      videoId: videoLink,
      playerVars: {
        'autoplay': 1
      },
      events: {
        'onReady': onPlayerReady
      }
  });
    }

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

The essence of the problem in the console: Uncaught ReferenceError: YT is not defined, i.e. in the onYouTubeIframeAPIReady function - YT was not defined when the player was created, which means that the previous function did not have time to work out. More precisely, the function worked, but the API did not have time to fully load, and the callback does not see it (this is how it seems to me). Checked by a deferred call to onYouTubeIframeAPIReady, i.e. via setTimeout - normally works. But I don't want to use setTimeout, something tells me that this is not the right solution.
Another trouble is that even if it works (by setTimeout), it only works on PC. And on Android, for example, it does not work, i.e. no video is loading or playing. And this story
completes this stack of problemsin Chrome. I don’t know, maybe this somehow affects the fact that Android does not load, but, in any case, to hell with it, I’ll figure it out later. For now, I’m wondering how to still call the onYouTubeIframeAPIReady function only when the previous one worked and the API was fully loaded?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
po5epT, 2018-02-24
@po5epT

You need to hang a handler on the onload event of the YouTube API download

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question