YouTube自动切换至最高清晰度脚本
一键获取地址
YouTube Auto HD-1.6.user.js
greasyfork获取
源代码
// ==UserScript==
// @name YouTube Auto HD
// @namespace https://blog.hgtrojan.com
// @version 1.6
// @description 自动选择最高画质的YouTube视频
// @author HgTrojan
// @match *://www.youtube.com/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
let highestQuality = null;
function setHighestQuality() {
const video = document.querySelector('video');
if (video) {
const player = document.querySelector('.html5-video-player');
if (player) {
const availableQualityLevels = player.getAvailableQualityLevels();
if (availableQualityLevels && availableQualityLevels.length > 0) {
highestQuality = availableQualityLevels[0];
console.log("Setting quality to: " + highestQuality);
player.setPlaybackQualityRange(highestQuality, highestQuality);
player.setPlaybackQuality(highestQuality);
// 在标签页标题中显示提示信息
displayMessage("设置画质为 " + highestQuality);
} else {
console.warn("Hgtrojan: 未能找到可用的清晰度级别");
}
} else {
console.warn("Hgtrojan: 未能找到视频播放器");
}
} else {
console.warn("Hgtrojan: 未能找到视频元素");
}
}
function checkAndMaintainHighestQuality() {
const video = document.querySelector('video');
if (video) {
const player = document.querySelector('.html5-video-player');
if (player && highestQuality) {
const currentQuality = player.getPlaybackQuality();
if (currentQuality !== highestQuality) {
console.log("Maintaining quality at: " + highestQuality);
player.setPlaybackQuality(highestQuality);
}
}
}
}
function checkUrlAndSetQuality() {
if (window.location.href.includes('watch')) {
setHighestQuality();
// 每隔5秒检查并保持最高画质
setInterval(checkAndMaintainHighestQuality, 5000);
}
}
function displayMessage(message) {
document.title = message;
// 10秒后恢复原来的标题
setTimeout(() => {
document.title = originalTitle;
}, 10000);
}
const originalTitle = document.title;
// 创建MutationObserver实例
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.addedNodes) {
mutation.addedNodes.forEach(function(node) {
if (node.nodeName === 'VIDEO') {
setTimeout(checkUrlAndSetQuality, 1000);
}
});
}
});
});
// 开始观察整个文档,包括所有子节点和后代节点
observer.observe(document, { childList: true, subtree: true });
// 初始加载时设置最高清晰度
window.addEventListener('yt-player-updated', checkUrlAndSetQuality);
window.addEventListener('yt-navigate-finish', checkUrlAndSetQuality);
})();
打赏: 支付宝
本人所有文章均为技术分享,均用于防御为目的的记录,所有操作均在实验环境下进行,请勿用于其他用途,否则后果自负。 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!