Browserify 破坏了 Youtube iFrame API

Browserify breaks Youtube iFrame API

当我浏览获取和应用 Youtube iFrame API 的脚本时,onYoutubeIframeAPIReady() 不会 运行,并且请求的视频不会加载。有没有解决的办法?我做错了什么吗?

这是我的脚本:

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);

onYouTubeIframeAPIReady 函数必须位于全局范围内,因此必须在 window 对象上定义。

所以在你使用 browserify 的情况下,你需要在 global 对象上定义它:

global.onYouTubeIframeAPIReady = function() {
  player = new YT.Player('player', {
    videoId: 'M7lc1UVf-VE',
    playerVars: {
      'controls': 1,
      'rel': 1,
    },
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
}