Skip to content

Instantly share code, notes, and snippets.

@abstraction
Created July 16, 2024 17:37
Show Gist options
  • Save abstraction/09ad30ee090d28ef14c0dce31fbe5b42 to your computer and use it in GitHub Desktop.
Save abstraction/09ad30ee090d28ef14c0dce31fbe5b42 to your computer and use it in GitHub Desktop.
Remove YouTube videos shorter than MIN_DURATION in YouTube search results
/**
* Run at https://www.youtube.com/results?search_query=*
* Remove YouTube videos shorter than MIN_DURATION in YouTube search results
*/
(function() {
const MIN_DURATION = 3600; // 1 hour in seconds
function convertToSeconds(duration) {
const parts = duration.split(':').map(part => parseInt(part, 10));
if (parts.length === 3) {
return parts[0] * 3600 + parts[1] * 60 + parts[2];
} else if (parts.length === 2) {
return parts[0] * 60 + parts[1];
}
return parts[0];
}
function hideVideos() {
const videoElements = document.querySelectorAll('ytd-video-renderer');
videoElements.forEach(videoElement => {
const timeElement = videoElement.querySelector('#text.ytd-thumbnail-overlay-time-status-renderer');
if (timeElement) {
const duration = timeElement.textContent.trim();
const seconds = convertToSeconds(duration);
if (seconds < MIN_DURATION) {
videoElement.style.display = 'none';
}
}
});
}
function removeEmptyShelves() {
const shelfRenderers = document.querySelectorAll('ytd-shelf-renderer');
shelfRenderers.forEach(shelf => {
const visibleVideos = shelf.querySelectorAll('ytd-video-renderer:not([style*="display: none"])');
if (visibleVideos.length === 0) {
shelf.style.display = 'none';
}
});
}
function filterVideos() {
hideVideos();
removeEmptyShelves();
}
// Init
filterVideos();
// FIXME: Set up mutation observer to handle dynamically loaded content
const observer = new MutationObserver(filterVideos);
observer.observe(document.querySelector('#contents'), { childList: true, subtree: true });
console.log('YouTube video filter activated. Hiding videos shorter than 1 hour.');
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment