// ==UserScript==
// @name 网页视频控制
// @namespace https://bbs.tampermonkey.net.cn/
// @version 0.1.0
// @description 通过键盘快捷键控制网页视频播放:空格键播放/暂停,左右方向键快退/快进,上下方向键调节音量
// @author Trae
// @match *://*/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
// 获取页面中的视频元素
function getVideoElement() {
return document.querySelector('video');
}
// 获取视频的唯一标识
function getVideoId(video) {
// 使用视频源和页面URL作为唯一标识
return `${window.location.href}-${video.currentSrc}`;
}
// 保存播放进度
function savePlaybackProgress(video) {
const videoId = getVideoId(video);
localStorage.setItem(videoId, video.currentTime.toString());
}
// 恢复播放进度
function restorePlaybackProgress(video) {
const videoId = getVideoId(video);
const savedTime = localStorage.getItem(videoId);
if (savedTime !== null) {
video.currentTime = parseFloat(savedTime);
}
}
// 键盘事件处理函数
function handleKeyPress(event) {
const video = getVideoElement();
if (!video) return;
// 防止按键事件影响页面其他功能
if (['Space', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(event.code)) {
event.preventDefault();
}
switch(event.code) {
case 'Space': // 空格键:播放/暂停
if (video.paused) {
video.play();
} else {
video.pause();
}
break;
case 'ArrowLeft': // 左方向键:后退5秒
video.currentTime = Math.max(0, video.currentTime - 5);
break;
case 'ArrowRight': // 右方向键:前进5秒
video.currentTime = Math.min(video.duration, video.currentTime + 5);
break;
case 'ArrowUp': // 上方向键:音量增加10%
video.volume = Math.min(1, video.volume + 0.1);
break;
case 'ArrowDown': // 下方向键:音量降低10%
video.volume = Math.max(0, video.volume - 0.1);
break;
}
}
// 添加键盘事件监听
document.addEventListener('keydown', handleKeyPress);
// 添加提示信息
const style = document.createElement('style');
style.textContent = `
.video-control-tips {
position: fixed;
bottom: 20px;
right: 20px;
background: rgba(0, 0, 0, 0.7);
color: white;
padding: 10px;
border-radius: 5px;
font-size: 14px;
z-index: 9999;
display: none;
}
`;
document.head.appendChild(style);
const tips = document.createElement('div');
tips.className = 'video-control-tips';
tips.innerHTML = `
视频控制快捷键:
空格键 - 播放/暂停
← → - 快退/快进5秒
↑ ↓ - 音量增加/减少
`;
document.body.appendChild(tips);
// 当视频存在时显示提示并设置相关功能
const observer = new MutationObserver(() => {
const video = getVideoElement();
if (video) {
// 显示提示
tips.style.display = 'block';
setTimeout(() => {
tips.style.display = 'none';
}, 5000);
// 视频加载完成后恢复播放进度
video.addEventListener('loadedmetadata', () => {
restorePlaybackProgress(video);
});
// 定期保存播放进度(每5秒)
setInterval(() => {
if (!video.paused) {
savePlaybackProgress(video);
}
}, 5000);
// 页面关闭或切换前保存进度
window.addEventListener('beforeunload', () => {
savePlaybackProgress(video);
});
observer.disconnect();
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
})();