Chrome扩展模拟将鼠标悬停在Youtube播放器上

时间:2017-08-07 09:55:20

标签: javascript jquery google-chrome-extension youtube

我正在为Youtube开发Chrome扩展程序,当用户点击我创建的按钮时,我想模拟鼠标悬停在播放器上,而不移动鼠标。播放视频时,手动将鼠标悬停在播放器上,控制(播放,暂停等)和进度条显示,这就是我要完成的操作,但只需单击按钮而不是悬停。< / p>

我不想暂停视频,只在用户点击我创建的按钮时显示底部控件和进度条。

的manifest.json

//name, description, background etc
"content_scripts": [
    {
      "matches": ["http://www.youtube.com/*", "https://www.youtube.com/*"],
      "js": ["jquery.js", "content.js"]
    }
  ]

content.js

$('#myButton').on('click', function() {

    //I have tried the following:
    $('#movie_player').trigger('mouseenter')
    $('#movie_player').mouseenter()
    document.getElementById('movie_player').onmouseenter()

    //I can play/pause the video with:
    $('#movie_player').click()
}

我也试过“mouseover”(jQuery)和“onmouseover”(javascript),我也在#movie_player的几个不同的子元素上尝试过这些但没有成功。

当手动悬停在播放器上时,Chrome的DevTools向我显示#movie_player元素有一个类(ytp-autohide),当鼠标进入/离开元素时,它会被删除/添加。然而。我不能在用户点击我的按钮时删除这个类,因为那时进度条/持续时间不会更新。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

如果有人感兴趣(在this extension的帮助下)

,则管理解决问题
$('#myButton').on('click', function() {
  const ytplayer = document.querySelector('.html5-video-player')
  const video = ytplayer.querySelector('video')
  const progressbar = ytplayer.querySelector('.ytp-play-progress')
  const loadbar = ytplayer.querySelector('.ytp-load-progress')

  //show controls and progress bar
  $('.html5-video-player').toggleClass('ytp-autohide')

  //update red progress bar
  video.addEventListener('timeupdate', updateProgressBar)
  function updateProgressBar() {
    progressbar.style.transform = 'scaleX('+(video.currentTime/video.duration)+')'
  }

  //update grey buffer progress
  video.addEventListener('progress', updateBufferProgress)
  function updateBufferProgress() {
    loadbar.style.transform = 'scaleX('+(video.buffered.end(video.buffered.length-1)/video.duration)+')'
  }

  //update current time
  $('.ytp-time-current').text(formatTime( video.currentTime ))

  //update current time every second
  const i = setInterval(function(){
    $('.ytp-time-current').text(formatTime( video.currentTime ))
  }, 1000)

  //stop after 3 seconds
  setTimeout(function() {
    $('.html5-video-player').toggleClass('ytp-autohide')
    clearInterval(i)
    video.removeEventListener('timeupdate',  updateProgressBar)
    video.removeEventListener('progress',  updateBufferProgress)
  }, 3000)
}

function formatTime(time){
  time = Math.round(time)

  const minutes = Math.floor(time / 60)
  let seconds = time - minutes * 60

  seconds = seconds < 10 ? '0' + seconds : seconds

  return minutes + ':' + seconds
}