YouTube Video Screenshot

Add video screenshot button for YouTube

当前为 2023-05-16 提交的版本,查看 最新版本

您需要先安装一个扩展,例如 篡改猴Greasemonkey暴力猴,之后才能安装此脚本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴Userscripts ,之后才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey,才能安装此脚本。

您需要先安装用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name          YouTube Video Screenshot
// @version       1.0.3
// @match         https://www.youtube.com/**
// @author        peng-devs
// @namespace     https://greasyfork.org/users/57176
// @description   Add video screenshot button for YouTube
// @icon          https://www.youtube.com/s/desktop/c1d331ff/img/favicon_48x48.png
// @grant         none
// @allFrames     true
// @license       MIT
// ==/UserScript==

(function() {
  'use strict'


  const NAME = 'YouTube Video Screenshot'


  function main() {
    if (!location.pathname.startsWith('/watch') &&
       !location.pathname.startsWith('/live'))
      return

    const observer = new MutationObserver(_ => {
      const control_bar = document.querySelector('.ytd-player.ytp-right-controls')
      if (!control_bar) return

      if (document.getElementById('yt-ss-btn')) return

      console.log(`[${NAME}] initializing...`)

      const button = document.createElement("button")
      button.id = 'yt-ss-btn'
      button.title = 'Screenshot'
      button.className = 'ytp-button style-scope ytd-player'
      button.innerHTML = `
        <svg viewBox="-6 -6 38 38" class="style-scope ytd-player">
          <path d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z"
                class="style-scope ytd-player"
                fill="#fff">
          </path>
        </svg>
      `

      button.onclick = () => {
        const video = document.querySelector('video')
        const canvas = document.createElement('canvas')
        canvas.width = video?.videoWidth
        canvas.height = video?.videoHeight
        canvas.getContext('2d')?.drawImage(video, 0, 0, canvas.width, canvas.height)

        // download screenshot directly
        const link = document.createElement('a')
        link.download = `yt-screenshot-${Date.now()}.png`
        link.href = canvas.toDataURL()
        link.click()
      }

      // place button on the player control bar
      control_bar.prepend(button)

      observer.disconnect()
      console.log(`[${NAME}] loaded`)
    })
    observer.observe(document.body, { childList: true, subtree: true })
  }

  main()
  document.addEventListener('yt-navigate-finish', main, true)

})();