Youtube Screenshot

Add screenshot button on Youtube Player

当前为 2022-04-19 提交的版本,查看 最新版本

// ==UserScript==
// @name        Youtube Screenshot
// @namespace   LeKAKiD
// @match       https://*.youtube.com/*
// @grant       none
// @version     1.2
// @author      -
// @description Add screenshot button on Youtube Player
// @license     MIT
// ==/UserScript==

(() => {
  const canvas = document.createElement('canvas');
  const context = canvas.getContext('2d');

  const button = document.createElement('button');
  button.classList.add('ytp-button');
  button.innerHTML = `<svg fill="none" height="100%" viewBox="-4 -4 28 28" width="100%">
  <path d="M6.5 5C5.67157 5 5 5.67157 5 6.5V8.5C5 8.77614 5.22386 9 5.5 9C5.77614 9 6 8.77614 6 8.5V6.5C6 6.22386 6.22386 6 6.5 6H8.5C8.77614 6 9 5.77614 9 5.5C9 5.22386 8.77614 5 8.5 5H6.5Z" fill="#fff"/>
  <path d="M11.5 5C11.2239 5 11 5.22386 11 5.5C11 5.77614 11.2239 6 11.5 6H13.5C13.7761 6 14 6.22386 14 6.5V8.5C14 8.77614 14.2239 9 14.5 9C14.7761 9 15 8.77614 15 8.5V6.5C15 5.67157 14.3284 5 13.5 5H11.5Z" fill="#fff"/>
  <path d="M6 11.5C6 11.2239 5.77614 11 5.5 11C5.22386 11 5 11.2239 5 11.5V13.5C5 14.3284 5.67157 15 6.5 15H8.5C8.77614 15 9 14.7761 9 14.5C9 14.2239 8.77614 14 8.5 14H6.5C6.22386 14 6 13.7761 6 13.5V11.5Z" fill="#fff"/>
  <path d="M15 11.5C15 11.2239 14.7761 11 14.5 11C14.2239 11 14 11.2239 14 11.5V13.5C14 13.7761 13.7761 14 13.5 14H11.5C11.2239 14 11 14.2239 11 14.5C11 14.7761 11.2239 15 11.5 15H13.5C14.3284 15 15 14.3284 15 13.5V11.5Z" fill="#fff"/>
  <path d="M3 5C3 3.89543 3.89543 3 5 3H15C16.1046 3 17 3.89543 17 5V15C17 16.1046 16.1046 17 15 17H5C3.89543 17 3 16.1046 3 15V5ZM4 5V15C4 15.5523 4.44772 16 5 16H15C15.5523 16 16 15.5523 16 15V5C16 4.44772 15.5523 4 15 4H5C4.44772 4 4 4.44772 4 5Z" fill="#fff"/>
  </svg>`;
  button.addEventListener('click', async (e) => {
    const video = document.querySelector('video');
    if(video?.tagName !== 'VIDEO') return;

    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;

    context.drawImage(video, 0, 0);
    const blob = await new Promise((resolve) => {
      canvas.toBlob((blob) => resolve(blob));
    });
    const item = new ClipboardItem({
      [blob.type]: blob,
    })
    navigator.clipboard.write([item]);
  });

  const observer = new MutationObserver(() => {
    const controls = document.querySelector('.ytp-right-controls');
    if(controls) {
      controls.prepend(button);
      observer.disconnect();
      return;
    }
  });
  observer.observe(document.documentElement, {
    childList: true,
    subtree: true,
  });
})();