Absolutely! Here’s a script you can inject into a YouTube watch page (e.g., via the browser console or a userscript manager like Tampermonkey). This script:
- Adds a button next to the Like button.
- On click, it:
- Gets available video qualities (from the YouTube player API).
- Sets the video to the second highest quality.
- Ensures the video is playing.
- Waits for the video to advance by at least one second (by monitoring
currentTime).
- Sets the video to the highest quality.
- Ensures the video is playing.
- Logs verbosely to the console at each step.
Note: This uses YouTube’s internal player API, which is accessible via window.ytplayer or document.querySelector('video') for some actions, but for quality selection, we need the YouTube player API.
(function() {
// Helper to log with a prefix
function vlog(...args) {
console.log('[YT Quality Script]', ...args);
}
// Wait for an element to appear
function waitForElement(selector, timeout = 10000) {
return new Promise((resolve, reject) => {
const el = document.querySelector(selector);
if (el) return resolve(el);
const observer = new MutationObserver(() => {
const el = document.querySelector(selector);
if (el) {
observer.disconnect();
resolve(el);
}
});
observer.observe(document.body, { childList: true, subtree: true });
setTimeout(() => {
observer.disconnect();
reject('Timeout waiting for ' + selector);
}, timeout);
});
}
// Get the YouTube player API
function getPlayer() {
// Try the global player
if (window.yt && window.yt.player && window.yt.player.getPlayerByElement) {
const player = window.yt.player.getPlayerByElement('movie_player');
if (player) return player;
}
// Try the global variable
if (window.ytplayer && window.ytplayer.config && window.ytplayer.config.args) {
return window.ytplayer;
}
// Try the player element
const playerEl = document.getElementById('movie_player');
if (playerEl && typeof playerEl.getAvailableQualityLevels === 'function') {
return playerEl;
}
return null;
}
// Get available quality levels
function getAvailableQualities(player) {
if (typeof player.getAvailableQualityLevels === 'function') {
return player.getAvailableQualityLevels();
}
if (player && player.getPlayerState && player.getPlaybackQuality) {
// Try to use the player API
return player.getAvailableQualityLevels();
}
return [];
}
// Set playback quality
function setQuality(player, quality) {
vlog('Setting quality to', quality);
if (typeof player.setPlaybackQualityRange === 'function') {
player.setPlaybackQualityRange(quality);
}
if (typeof player.setPlaybackQuality === 'function') {
player.setPlaybackQuality(quality);
}
}
// Ensure video is playing
function ensurePlaying(player, videoEl) {
return new Promise((resolve) => {
const state = typeof player.getPlayerState === 'function' ? player.getPlayerState() : null;
// 1 = playing, 2 = paused
if (state === 1) {
vlog('Video already playing');
resolve();
} else {
vlog('Attempting to play video');
if (typeof player.playVideo === 'function') {
player.playVideo();
} else if (videoEl && typeof videoEl.play === 'function') {
videoEl.play();
}
// Wait for play event
if (videoEl) {
videoEl.addEventListener('playing', function handler() {
videoEl.removeEventListener('playing', handler);
vlog('Video is now playing');
resolve();
});
} else {
setTimeout(resolve, 1000); // fallback
}
}
});
}
// Wait for video to advance by at least one second
function waitForAdvance(videoEl, seconds = 1) {
return new Promise((resolve) => {
const start = videoEl.currentTime;
vlog('Waiting for video to advance by', seconds, 'second(s). Start time:', start);
function check() {
const now = videoEl.currentTime;
if (now - start >= seconds) {
vlog('Video advanced by', now - start, 'seconds');
resolve();
} else {
requestAnimationFrame(check);
}
}
check();
});
}
// Add button next to Like button
async function addButton() {
try {
// Wait for the Like button
const likeBtn = await waitForElement('ytd-toggle-button-renderer:nth-of-type(1) #button');
if (document.getElementById('yt-quality-script-btn')) {
vlog('Button already exists');
return;
}
// Create our button
const btn = document.createElement('button');
btn.id = 'yt-quality-script-btn';
btn.textContent = 'Quality Switch';
btn.style.marginLeft = '8px';
btn.style.padding = '6px 12px';
btn.style.background = '#065fd4';
btn.style.color = '#fff';
btn.style.border = 'none';
btn.style.borderRadius = '2px';
btn.style.cursor = 'pointer';
btn.style.fontWeight = 'bold';
likeBtn.parentNode.insertBefore(btn, likeBtn.nextSibling);
btn.addEventListener('click', async () => {
vlog('Button clicked');
const player = getPlayer();
if (!player) {
vlog('Could not find YouTube player API');
return;
}
const videoEl = document.querySelector('video');
if (!videoEl) {
vlog('Could not find video element');
return;
}
let qualities = getAvailableQualities(player);
vlog('Available qualities:', qualities);
if (!qualities || qualities.length < 2) {
vlog('Not enough quality levels available');
return;
}
// YouTube returns qualities from highest to lowest
const highest = qualities[0];
const secondHighest = qualities[1];
vlog('Setting to second highest quality:', secondHighest);
setQuality(player, secondHighest);
await ensurePlaying(player, videoEl);
await waitForAdvance(videoEl, 1);
vlog('Setting to highest quality:', highest);
setQuality(player, highest);
await ensurePlaying(player, videoEl);
vlog('Done!');
});
vlog('Button added next to Like button');
} catch (e) {
vlog('Error adding button:', e);
}
}
addButton();
})();
How it works:
- The script waits for the Like button, then adds a new button next to it.
- On click, it uses the YouTube player API to get available qualities, sets to the second highest, waits for the video to advance, then sets to the highest.
- It uses the video element’s
currentTime to ensure the video has actually advanced.
- Verbose logging is provided at every step.
Tested on: YouTube as of June 2024.
Note: YouTube’s internal APIs can change, so this may need updates in the future. If you need a version for a userscript manager (like Tampermonkey), let me know!