如何在YouTube播放器上删除事件监听器?

时间:2018-09-12 19:47:06

标签: youtube-api youtube-iframe-api

在播放我们嵌入的youtube视频时,我需要发送一些统计信息,但是只有当用户第一次播放视频时,我才应该删除事件监听器。 我的问题是如何使用Google Youtube API?

player.removeEventListener(event:String, listener:String):Void似乎根本不起作用。

这是一个简化的测试用例:

'use strict'

function onPlayerStateChange ({ data, target }) {
  const sendClickLink = data === YT.PlayerState.PLAYING
  const annotationID = target.getIframe().id

  if (sendClickLink) {
    console.log('send stats', annotationID)
    unlistenPlayer(target)
  }
}

function createPlayer ({ annotationID, videoId }) {
  const player = new YT.Player(annotationID, { videoId })
  player.addEventListener('onStateChange', 'onPlayerStateChange')
  console.log('createPlayer', annotationID)
  return player
}

function unlistenPlayer (player) {
  player.removeEventListener('onStateChange', 'onPlayerStateChange')
  console.log('unlistenPlayer', player.getIframe().id)
}

window.onYouTubeIframeAPIReady = function onYouTubeIframeAPIReady () {
  createPlayer({
    videoId: 'a2-1yVxaxuI',
    annotationID: '004ET3NX1RANJ5X51R0P288ZMN'
  })
}

下面是执行上述操作的一些HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Youtube removeEventListener</title>
  <script src="https://www.youtube.com/iframe_api" defer></script>
  <script>
     // insert above javascript here
  </script>
</head>
<body>
  <iframe
    id="004ET3NX1RANJ5X51R0P288ZMN"
    src="https://www.youtube.com/embed/a2-1yVxaxuI?enablejsapi=1"
    class="annotation annotation__youtube"
    frameborder="0"
    allowfullscreen="true"
    allowtransparency="true"
    allow="encrypted-media"
    tabindex="1"
    style="width: 311.204px; height: 170.244px;"></iframe>
</body>
</html>

0 个答案:

没有答案