百度网盘自动打开中文字幕
当前为
// ==UserScript==
// @name 百度网盘打开中文字幕(改)
// @namespace http://tampermonkey.net/
// @version 1.41
// @description 百度网盘自动打开中文字幕
// @author woshilisisui
// @match https://pan.baidu.com/pfile/video?path=*.mp4*
// @icon https://th.bing.com/th?id=ODLS.039b3eb8-253e-4d80-8727-6e7d039c3891&w=32&h=32&qlt=90&pcl=fffffa&o=6&pid=1.2
// @grant GM_addStyle
// @grant unsafeWindow
// @license GPL3
// ==/UserScript==
(function () {
'use strict';
/* 修改字幕的样式,不喜欢可以删除或修改 */
GM_addStyle(`
.vp-video__subtitle-text.show {
background: rgba(214, 214, 214, 0.65) !important;
color: #ff0000 !important;
}
`);
/* 修改字幕样式 */
// 隐藏大播放按钮
GM_addStyle(`
.vjs-big-play-button { display: none !important; }
`);
// 控制条样式
GM_addStyle(`
.auto-hide-controlbar {
opacity: 0 !important;
pointer-events: none !important; /* 禁止点击 */
transition: opacity 0.3s;
}
.auto-hide-controlbar.show {
opacity: 1 !important;
pointer-events: auto !important; /* 显示时可点击 */
}
`);
const controlSelectors = [
'.video-js .vjs-control-bar',
'.vp-video .vp-video__control-bar',
'.vp-file-video-container__tools',
'.vp-video .vp-video__control-bar--play-time-current',
'.vp-video .vp-video__control-bar--play-time-all'
];
// 动态等待控制条加载
function waitForElements(selectors, callback, interval = 500, maxAttempts = 40) {
let attempts = 0;
const timer = setInterval(() => {
const elements = selectors.map(sel => document.querySelector(sel));
if (elements.every(el => el)) {
clearInterval(timer);
callback(elements);
} else if (++attempts >= maxAttempts) {
clearInterval(timer);
console.warn('控制条元素未找到');
}
}, interval);
}
waitForElements(controlSelectors, (elements) => {
console.log('控制条加载完成', elements);
elements.forEach(el => el.classList.add('auto-hide-controlbar'));
let hideTimer = null;
const player = document.querySelector('.vp-video, .video-js');
if (player) {
player.addEventListener('mousemove', () => {
// 鼠标移动 → 显示控制条
elements.forEach(el => el.classList.add('show'));
// 清理之前定时器
clearTimeout(hideTimer);
// 鼠标不动 1 秒后隐藏
hideTimer = setTimeout(() => {
elements.forEach(el => el.classList.remove('show'));
}, 1000);
});
// 鼠标移出播放器区域 → 立即隐藏
player.addEventListener('mouseleave', () => {
clearTimeout(hideTimer);
elements.forEach(el => el.classList.remove('show'));
});
}
});
//
const w = unsafeWindow;
let interval
// 等待页面完全加载完毕后执行脚本
window.onload = function() {
let lastUrl = '' // 存储上一个 URL
// 监听 DOM 变化
const observer = new MutationObserver(() => {
const currentUrl = window.location.href;
// 检查 URL 是否发生变化
if (currentUrl !== lastUrl) {
console.log('URL发生变化');
lastUrl = currentUrl; // 更新上一个 URL
//controlBDisplay();
//controlB();
setTimeout(() => {
simulateMouseHoverToButton();
}, 0);
clearInterval(interval); // 停止当前轮询
// URL 变化后稍微延迟一段时间再检测,确保 DOM 完全更新
setTimeout(() => {
waitForSubtitleButton();
checkAddDownloadButton();
}, 0);
}
});
// 开始观察 DOM 变化,监听整个页面的变化
observer.observe(document.body, { childList: true, subtree: true });
function waitForSubtitleButton() {
const maxAttempts = 100; // 设置最大尝试次数
let attempts = 0;
interval = setInterval(function () {
attempts++;
if (attempts >= maxAttempts) {
console.log('尝试次数过多,停止轮询');
console.log('不存在中文字幕');
clearInterval(interval);
return
}
simulateMouseHoverToButton();
// 获取所有符合条件的元素
const subtitleElements = document.querySelectorAll('li.vp-video__control-bar--video-subtitles-select-item');
console.log(subtitleElements)
if (subtitleElements && subtitleElements.length > 0) {
// 遍历所有符合条件的元素
subtitleElements.forEach(element => {
console.log(element.textContent);
// 检查元素的文本内容是否为“中文字幕”
if (element.textContent.trim() === '中文字幕') {
clearInterval(interval); // 停止检测
console.log('检测到中文字幕,进行点击...');
element.click(); // 模拟点击操作
}
});
}
}, 2000);
}
function simulateMouseHoverToButton() {
// 获取需要悬停的按钮
const buttonElement = document.querySelector('.vp-video__control-bar--button.is-text');
console.log(buttonElement);
if (buttonElement) {
// 创建一个鼠标事件
const mouseOverEvent = new MouseEvent('mouseenter', {
view: w,
bubbles: true,
cancelable: true
});
// 触发鼠标悬停事件
buttonElement.dispatchEvent(mouseOverEvent);
console.log('鼠标悬停到按钮上');
setTimeout(() => {
// 创建一个鼠标移开事件
const mouseLeaveEvent = new MouseEvent('mouseleave', {
view: w,
bubbles: true,
cancelable: true
});
// 触发鼠标移开事件
buttonElement.dispatchEvent(mouseLeaveEvent);
console.log('鼠标移开按钮');
}, 500);
} else {
console.log('未找到需要悬停的按钮');
}
}
// 下载字幕
function clearResources() {
performance.clearResourceTimings();
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function retryOperation(operation, maxRetries = 3, delay = 1000) {
for (let i = 0; i < maxRetries; i++) {
try {
return await operation();
} catch (error) {
if (i === maxRetries - 1) throw error;
console.log(`尝试失败,${maxRetries - i - 1}次重试后重新尝试`);
await sleep(delay);
}
}
}
async function findSubtitleUrl() {
const resources = performance.getEntriesByType("resource");
let matchedUrls = resources.filter(resource => resource.name.includes('netdisk-subtitle'));
if (matchedUrls.length > 0) {
let url = matchedUrls[matchedUrls.length - 1].name;
console.log('找到匹配的URL:', url);
return url;
} else {
throw new Error('未找到匹配的URL');
}
}
async function downloadSubtitle() {
let button = document.querySelector('li.vp-video__control-bar--video-subtitles-select-item.is-checked');
clearResources(); // 清理资源
if (button.classList.contains('is-normal')) {
button = document.querySelector('ul.vp-video__control-bar--video-subtitles-select-group.is-large li:nth-child(2)');
}
button.click();
await sleep(500);
try {
// 获取字幕名称
// const url = await retryOperation(findSubtitleUrl);
// const regex = /fn=(.*)\.mp4/;
// let fileName = decodeURIComponent(url.match(regex)[1]).replace('+', ' ') + '.srt';
// 获取视频名称
const url = window.location.href;
const params = new URLSearchParams(url.split('?')[1]);
const path = params.get('path'); // /公务员/.../赠送:课后作业 4.mp4
const fileName = path.match(/([^/]+)(?=\.[^.]+$)/)[0] + '.srt';
console.log(fileName);
// 使用 Fetch 获取字幕文件内容
const response = await fetch(url);
if (!response.ok) throw new Error('获取字幕文件失败');
const subtitleText = await response.text();
// 创建一个 Blob 对象用于下载
const blob = new Blob([subtitleText], { type: 'text/plain' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = fileName;
// 自动点击下载链接
link.click();
} catch (error) {
console.error('下载失败:', error);
}
}
// 深色模式切换后重新添加下载字幕按钮
function colorButtonBind() {
// console.log('1111111111')
const colorButton = document.querySelector('div.vp-toolsbar__more-group > button:nth-child(1)')
// console.log('2222222222'+colorButton)
colorButton.addEventListener('click', addDownloadButton);
// console.log('3333333333'+colorButton)
}
function addDownloadButton() {
//const controlBar = document.querySelector("#vjs_video_594 > section > div.vp-video__control-bar--setup > div:nth-child(1) > div > div.vp-inner-vontainer > div > div.vp-video__control-bar--video-subtitles > div > ul");
const controlBar = document.querySelector('.vp-video-player .vp-video__control-bar .vp-video__control-bar--video-subtitles .vp-video__control-bar--video-subtitles-select .vp-video__control-bar--video-subtitles-select-group')
// console.log(controlBar)
if (controlBar) {
// let downloadButton = controlBar.querySelector('button.download-subtitle');
const controlBox = document.querySelector('div.vp-toolsbar__tools')
let downloadButton = controlBox.querySelector('button.download-subtitle');
// 获取第三个子节点
if (!downloadButton) {
console.log('创建字幕下载按钮!');
// 如果按钮不存在,则创建一个新的按钮
downloadButton = document.createElement('button');
downloadButton.type = 'button'
downloadButton.className = 'vp-btn normal is-round vp-toolsbar__tools-btn download-subtitle'; // 添加类名方便识别
// downloadButton.textContent = '下载字幕';
downloadButton.title = '下载字幕';
const i = document.createElement('i');
i.className = 'u-icon-download-bold'
const span = document.createElement('span');
span.textContent = '字幕'
const thirdChild = controlBox.children[2];
if (thirdChild) {
// 在第三个子节点前插入新元素
controlBox.insertBefore(downloadButton, thirdChild);
} else {
// 如果没有第三个子节点,直接添加到末尾
controlBox.appendChild(downloadButton);
}
downloadButton.appendChild(i)
downloadButton.appendChild(span)
// controlBox.appendChild(downloadButton);
console.log('创建成功!');
}
// console.log(downloadButton)
// 更新按钮的点击事件
downloadButton.removeEventListener('click', downloadSubtitle); // 移除旧的事件处理器
downloadButton.addEventListener('click', downloadSubtitle); // 添加新的事件处理器
// 重新绑定
colorButtonBind()
return true;
}
return false;
}
function checkAddDownloadButton() {
const checkFunction = setInterval(() => {
if (addDownloadButton()) {
console.log("检测到下载按钮,停止轮询");
clearInterval(checkFunction); // 停止轮询
}
}, 500); // 每 500ms 检查一次
}
}
})();