When I Browserify a script that acquires and apply's the Youtube iFrame API, onYoutubeIframeAPIReady()
does not run, and the requested video does not load. Is there a way around this? Am I doing something wrong?
Here's my script:
var Command = require('../model/command.js');
var Control = require('../model/control.js');
var User = require('../model/user.js');
var socket = io();
var executions = {};
executions[1] = function() { player.playVideo(); };
executions[2] = function() { player.pauseVideo(); };
var control = Control();
var now = function() { return new Date().getTime() / 1000; };
var user = User();
var update = function() {
control.room = $('#name').text();
if (user.last) {
if (user.command.date > user.last) {
player.seekTo(user.command.time, true);
executions[user.command.state]();
control.last = user.command.date;
}
} else {
player.seekTo(user.time, true);
executions[user.state]();
control.last = now();
}
control.time = player.getCurrentTime();
control.state = player.getPlayerState();
socket.emit('control', control);
};
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
videoId: 'M7lc1UVf-VE',
playerVars: {
'controls': 1,
'rel': 1,
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
$('#youtube-controls').show();
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.Playing) {}
}
$('#youtube-controls').hide();
// Control
$('#pause').click(function() {
player.pauseVideo();
control.command = Command(2, player.getCurrentTime());
});
$('#play').click(function() {
player.playVideo();
control.command = Command(1, player.getCurrentTime());
});
// Input
socket.on('update', function(message) { user = message; });
// Output
setInterval(update, 1000);
The onYouTubeIframeAPIReady
function must be located in the global scope so it has be to defined on the window
object.
So in your case with browserify you need to define it on the global
object:
global.onYouTubeIframeAPIReady = function() {
player = new YT.Player('player', {
videoId: 'M7lc1UVf-VE',
playerVars: {
'controls': 1,
'rel': 1,
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}