Skip to content

Instantly share code, notes, and snippets.

@trapke
Created March 1, 2021 22:46
Show Gist options
  • Save trapke/b738f20990cb3898b47dd3e17074d03a to your computer and use it in GitHub Desktop.
Save trapke/b738f20990cb3898b47dd3e17074d03a to your computer and use it in GitHub Desktop.
Tampermonkey script to automatically pause videos and run it in mpv
// ==UserScript==
// @name mpvyoutube
// @namespace mpvyoutube
// @version 0.1
// @description Stops video and starts it in mpv. Original code: https://greasyfork.org/de/scripts/370504-youtube-stop-video-autoplay/code
// @author You
// @match https://www.youtube.com/*
// @grant none
// ==/UserScript==
var Debug = false
/**
* @default
* @constant
*/
const urlPath = '/watch'
/**
* Stop YouTube Video Player
*/
let stopPlayback = () => {
window.open('mpvyoutube://' + window.location.href, '_blank')
console.debug('stopPlayback')
// Video Playback Events
const eventList = ['play', 'playing', 'timeupdate']
eventList.forEach((eventName) => {
const videoElement = document.querySelector('video')
/** @listens video:Event */
videoElement.addEventListener(eventName, () => {
console.debug('videoElement', eventName)
const playerElement = document.querySelector('.html5-video-player')
// Pause Video
playerElement.pauseVideo()
// Status
console.info('Stopped Playback', 'Media Event:', eventName, 'Player State:', playerElement.getPlayerState())
}, { once: true })
})
}
/**
* Init
*/
let init = () => {
console.info('init')
// Check URL
if (!window.location.pathname.startsWith(urlPath)) { return }
// Stop Playback
stopPlayback()
}
/**
* Handle in-page navigation (classic YouTube)
* @listens window:Event#spfdone
*/
window.addEventListener('spfdone', () => {
console.debug('window#spfdone')
init()
})
/**
* Handle in-page navigation (modern YouTube)
* @listens window:Event#yt-navigate-finish
*/
window.addEventListener('yt-navigate-finish', () => {
console.debug('window#yt-navigate-finish')
init()
})
/**
* Handle in-page initial page loading, reloading
* @listens document:Event#readystatechange
*/
document.addEventListener('readystatechange', () => {
console.debug('document#readystatechange', document.readyState)
if (document.readyState === 'interactive') { init() }
})
@AgungSukaAFK
Copy link

AgungSukaAFK commented Jan 25, 2024

do you know how to make script that automatically pause a music playing from "music.youtube,com" when a video from "www.youtube.com" is playing, vice versa.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment