Youtube видео не воспроизводится во втором ajaxcall - PullRequest
0 голосов
/ 04 октября 2019

У меня есть рабочая область видео на YouTube, которая называется ajax. При первом входе посетителя в эту область видео работает отлично. Если посетитель переходит в другую область приложения и возвращает (второй вызов ajax), область видео не показывает никакого видео, и кажется, что window.onYouTubeIframeAPIReady () никогда не вызывается (ни событие onReady, которое вызывает playVideo () ...)

цель состоит в том, чтобы всегда показывать видео

Когда код один и тот же, но имеет другое поведение, я попытался динамически вставить и удалить youtube_api, сделайте window.onYouTubeIframeAPIReady () обнулить и восстановить, чтобы второй вызов был точно таким же, как первый, но ничего (я думаю, я не совсем понимаю, в чем проблема)

Код JavaScript:

function loadScript() {

    if (typeof (YT) == 'undefined' || typeof (YT.Player) == 'undefined') {
        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 loadPlayer() {


console.log(window.onYouTubePlayerAPIReady)


console.log("3");


    window.onYouTubePlayerAPIReady = function () {

        console.log("4");

        onYouTubeIframeAPIReady();

        console.log("5");
    };

}


$(function () {
    loadScript();
})



var VidID;


$(document).ready(function() {



console.log("0");



VidID = $("#videoWraper").attr("data-PlayingVid");

console.log("1");

loadPlayer();

console.log("2");




});



function onYouTubeIframeAPIReady() {

console.log("7");
player = new window.YT.Player('YouTubeVideo', {
    videoId: VidID, // YouTube Video ID lUlOptJolAA
    //width: 560,               // Player width (in px)
    //height: 3160,              // Player height (in 316 px)
    playerVars: {
        enablejsapi: 1,
        autoplay: 1,        // Auto-play the video on load
        controls: 1,        // Show pause/play buttons in player
        showinfo: 0,        // Hide the video title
        modestbranding: 1,  // Hide the Youtube Logo
        loop: 0,            // Run the video in a loop
        fs: 0,              // Hide the full screen button
        cc_load_policy: 1, // Hide closed captions
        iv_load_policy: 3,  // Hide the Video Annotations
        autohide: 1,         // Hide video controls when playing
        rel: 0,           // Hide recommended videos
    },

    events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
    }
});

console.log("8");
}

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

Как уже упоминалось, видео на YouTube работает при первом вызове, но не при втором.

Консольный трек (я вставил console.logs, чтобы получить эту информацию):

0 //starts
VM9066:53 1 // got to video ID
VM9066:15 undefined //window.onYouTubePlayerAPIReady not defined
VM9066:19 3
VM9066:58 2
VM9066:69 7 // window.onYouTubePlayerAPIReady is being defined
VM9066:94 8 // window.onYouTubePlayerAPIReady is defined
VM9066:24 4
VM9066:69 7 //dont understand why the second time
VM9066:94 8 //dont understand why the second time
VM9066:28 5
ERROR: www-widgetapi.js:115 Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://www.youtube.com') does not match the recipient window's origin ('http://localhost:44600').
ERROR: www-widgetapi.js:115 Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://www.youtube.com') does not match the recipient window's origin ('http://localhost:44600').
VM9066:104 10 //event onstatechange
VM9066:106 a1[object Object]
VM9066:107 a20

На второй консоли вызова AJAX просто показывает:

0
VM9574:53 1
VM9574:15 ƒ () {

        console.log("4");

        onYouTubeIframeAPIReady();

        console.log("5");
    }
VM9574:19 3
VM9574:58 2

HTML-код:

<div id="videoWraper" class="video-container" data-PlayingVid="@Model.SM_Identifier">
        <div id="YouTubeVideo"></div>
        <script async src="https://www.youtube.com/iframe_api"></script>
</div>

Пожалуйста, если кто-то может помочь мне найти ошибку, я бы очень признателенe it.

Спасибо и простите за длинный пост.

Ответы [ 2 ]

0 голосов
/ 09 октября 2019

Ответ на этот вопрос был найден в ответе на аналогичный вопрос:

https://stackoverflow.com/a/48038558/2358046

Вместо того, чтобы сделать внешний вызов, он выполняет внутренний вызов того же кода с незначительнымизменяется, решая ошибку:

ERROR: www-widgetapi.js:115 Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://www.youtube.com') does not match the recipient window's origin ('http://localhost:44600')

Это делает ненужной динамическую загрузку yt_api, поэтому сценарий js изменяется на:

var player;
var VidID;


//When ready, gets YT_ID and calls API do youtube
$(document).ready(function () {

VidID = $("#videoWraper").attr("data-PlayingVid");
    onYouTubeIframeAPIReady();
});




// Call to youtube API (internal) to start the video
function onYouTubeIframeAPIReady() {

player = new window.YT.Player('YouTubeVideo', {
    videoId: VidID, // YouTube Video ID lUlOptJolAA
    playerVars: {
        enablejsapi: 1,
        autoplay: 1,        // Auto-play the video on load
        controls: 1,        // Show pause/play buttons in player
        showinfo: 0,        // Hide the video title
        modestbranding: 1,  // Hide the Youtube Logo
        loop: 0,            // Run the video in a loop
        fs: 0,              // Hide the full screen button
        cc_load_policy: 1, // Hide closed captions
        iv_load_policy: 3,  // Hide the Video Annotations
        autohide: 1,         // Hide video controls when playing
        rel: 0,           // Hide recommended videos
    },

    events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
    }
});

}


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

Созданные файлы должны быть загружены перед этим кодом.

Монолитно и не идеально, но решает проблему.

0 голосов
/ 04 октября 2019

При первом вызове видео напрямую связывается со страницей, но при втором вызове ajax оно выполняется через локальный хост, который выдает перекрестный запрос запроса заголовков кабеля

...