Encountering an unusual problem with the Youtube API... I am in the process of developing a script that identifies all Youtube videos on a webpage and then replaces them using the Youtube API. This approach enables me to monitor API events like video completion to display custom messages. For each video on the page, I create a new instance of the Youtube player object which has been functioning smoothly thus far.
I dynamically produce video containers and store the container ID along with the video ID into an array of objects (see my current code below).
The peculiar issue arises when I generate this dynamic array of objects (via array.push()), resulting in Youtube API failing to function as intended. Conversely, explicitly declaring the array of objects ensures proper operation of the Youtube API.
To illustrate, here's an example where the Youtube API does not function properly:
var playerInfoList = [];
foreach loop{
playerInfoList.push( object );
}
Screenshot:
Conversely, this method works:
var playerInfoList = [
{containerID:'social_share_custom_0', videoID:'KSyHWMdH9gk'},
{containerID:'social_share_custom_1', videoID:'b-u5LE6X6ME'}
];
Screenshot:
I have created a demo page to showcase this issue, you can access it here:
<html>
<head>
</head>
<body>
<!-- PHP code omitted for brevity -->
//Load Yotube API
var tag = document.createElement("script");
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
/*
// if we declare this explicitly, Youtube API works.
// if this array if generated DYNAMICALLY (if we comment this out), Youtube API does not work.
*/
console.log( 'Object array length: ' + playerInfoList.length );
function onYouTubeIframeAPIReady() {
if(typeof playerInfoList === 'undefined')
return;
for(var i = 0; i < playerInfoList.length;i++) {
var player = createPlayer(playerInfoList[i]);
}
}
// Remaining Javascript functions remain unchanged...
</body>
</html>
After spending nearly two days exploring different solutions, I remain puzzled by the cause of this issue. Despite scouring resources for similar problems, I haven't come across a comparable scenario involving dynamically generated object arrays and the Youtube API.
Your assistance in resolving this matter would be greatly appreciated. Feel free to request additional information if needed. Thank you to those willing to offer support :)