Skip to content

Instantly share code, notes, and snippets.

@jdb8
Created November 28, 2021 07:27
Show Gist options
  • Save jdb8/b76d958e9bd89a79875884a4180867ae to your computer and use it in GitHub Desktop.
Save jdb8/b76d958e9bd89a79875884a4180867ae to your computer and use it in GitHub Desktop.
Auto-enable Picture-in-Picture (PiP) mode when scrolling past a YouTube video
// ==UserScript==
// @name Auto PiP for Youtube
// @version 0.1
// @description Auto-enable PiP when scrolling past a YouTube video
// @author Joe Bateson
// @match https://www.youtube.com/watch*
// @icon https://www.google.com/s2/favicons?domain=youtube.com
// @grant none
// ==/UserScript==
async function startPip(video) {
if (document.pictureInPictureElement) {
return;
}
try {
await video.requestPictureInPicture();
} catch (e) {
console.error(e);
}
}
(function() {
'use strict';
if (!document.pictureInPictureEnabled) {
// Immediately return if PiP is unavailable
return;
}
let pipShouldBeShown = false;
const video = document.querySelector('video');
document.addEventListener('click', () => {
// PiP cannot be activated unless a trusted user gesture was just performed
// For this reason we try to launch PiP any time one occurs
// TODO: respond to more than just 'click'
if (pipShouldBeShown) {
startPip(video);
}
});
let options = {
rootMargin: '0px',
threshold: 1.0
}
let observer = new IntersectionObserver(entries => {
// We only expect one intersection event each time
const isIntersecting = entries[0].isIntersecting;
if (!isIntersecting) {
// Try starting PiP in case a user event has just taken place
startPip(video);
// Otherwise remember for next time
pipShouldBeShown = true;
} else {
// Remember that we don't want PiP for now
pipShouldBeShown = false;
// Can always exit PiP safely, even without a trusted event
document.exitPictureInPicture();
}
}, options);
observer.observe(video);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment