// ==UserScript== // @name 视频网页全屏播放 // @name:en Video Web Fullscreen Player // @namespace https://scriptcat.org/zh-CN/users/222432 // @version 1.1.2 // @description 把网页视频变成网页全屏(网页内全屏,不是系统全屏)。操作逻辑照 B 站:点一下视频按 H,空格暂停,←/→ 快进退,C/X 调倍速,↑/↓ 音量,按住方向键 2 倍速 // @description:en Webpage fullscreen for any web video (in-page, not OS fullscreen). Bilibili-style keys: click the video then press H, Space to play/pause, arrows to seek, C/X for speed, Up/Down for volume, hold an arrow for 2x. // @icon data:image/png;base64,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 // @author beiyue // @license MIT // @match *://*/* // @grant none // @run-at document-idle // ==/UserScript== /* * —— 致谢 / Credits —— * 本脚本基于 @工具达人 的《网页视频倍速播放器·视频全页面播放适配·视频网页全屏》(v0.1) 重写。 * 原作地址:https://scriptcat.org/zh-CN/script-show-page/2866 * * 沿用原作的设计:H 键切换网页全屏、C / X / Z 倍速、方向键快进与音量、点击画面暂停、 * 中央提示气泡 + 底部进度条。 * 本版重写的部分:object-fit 尺寸适配、DOM/样式精确还原、监听器不泄漏、直播与未知时长保护、 * 倍速内部状态推进、C / X 倍速阶梯、点击聚焦后才响应 H、长按 2× 加速、多视频挑选等。 * 若原作者对本版有任何异议,请在本脚本页面留言,我会立即下架或把改动转交给原作者。 */ (function () { 'use strict'; const Z_ROOT = 2147483646; const MIN_W = 160; const MIN_H = 90; const RATE_MIN = 0.1; const RATE_MAX = 16; // C / X 共用的倍速梯子(升序):C 取上一个更大的档,X 取下一个更小的档 // 1 → 1.25 → 1.5 → 2 → 3 → 5 → 9 → 16 步长 0.25 / 0.25 / 0.5 / 1 / 2 / 4 … // 1 → 0.75 → 0.5 → 0.4 → 0.3 → 0.2 → 0.1 前两档 0.25,之后每档 0.1 const RATE_LADDER = [0.1, 0.2, 0.3, 0.4, 0.5, 0.75, 1, 1.25, 1.5, 2, 3, 5, 9, 16]; const RATE_PRESETS = [0.5, 1, 1.25, 1.5, 2, 3]; const IDLE_MS = 2500; const HINT_MS = 900; const HOLD_MS = 200; // 按住超过这个时间算「长按」,切 2x const HOLD_RATE = 2; // 长按时的固定倍速 const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v)); const fmtRate = (r) => `${Math.round(r * 100) / 100}x`; function formatTime(sec) { if (!isFinite(sec) || sec < 0) return '--:--'; const t = Math.floor(sec); const h = Math.floor(t / 3600); const m = Math.floor((t % 3600) / 60); const s = t % 60; const p = (n) => String(n).padStart(2, '0'); return h > 0 ? `${h}:${p(m)}:${p(s)}` : `${m}:${p(s)}`; } // 穿透 shadow DOM 取真实事件目标 function realTarget(e) { if (typeof e.composedPath === 'function') { const path = e.composedPath(); if (path && path.length) return path[0]; } return e.target; } function isEditable(el) { if (!el || el.nodeType !== 1) return false; const tag = el.tagName; if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || tag === 'OPTION') return true; if (el.isContentEditable) return true; if (typeof el.closest === 'function') { return !!(el.closest('input,textarea,select,[contenteditable=""],[contenteditable="true"],[contenteditable="plaintext-only"]')); } return false; } function makeButton(label, title) { const btn = document.createElement('button'); btn.type = 'button'; btn.className = 'vfp-btn'; btn.textContent = label; if (title) btn.title = title; return btn; } // 注意:视频自身 z-index 取 0,控制条(2)、提示(3) 才会盖在画面之上 const VIDEO_STYLE = { position: 'relative', 'z-index': '0', width: '100%', height: '100%', 'max-width': '100%', 'max-height': '100%', 'min-width': '0', 'min-height': '0', 'object-fit': 'contain', background: 'transparent', margin: '0', padding: '0', border: '0', 'border-radius': '0', 'box-shadow': 'none', transform: 'none', display: 'block', cursor: 'pointer' }; // iframe 播放器:只改样式、不搬节点(搬 iframe 会触发重新加载,等于把播到一半的视频重置了) const FRAME_STYLE = { position: 'fixed', top: '0', left: '0', 'z-index': '2147483645', width: '100vw', height: '100vh', 'max-width': 'none', 'max-height': 'none', 'min-width': '0', 'min-height': '0', margin: '0', padding: '0', border: '0', 'border-radius': '0', background: '#000', display: 'block', transform: 'none' }; class VideoFullpage { constructor() { this.activeVideo = null; this.lastVideo = null; this.state = null; this.ui = null; this.listeners = []; this.hideTimer = 0; this.hintTimer = 0; this.watchTimer = 0; this.holdTimer = 0; this.recheckTimer = 0; this.mode = 'video'; this.backdrop = null; this.dragging = false; this.rate = 1; this.boosting = false; this.pendingSeek = null; this.remote = false; this.remoteTimer = 0; // 点击聚焦:只有「刚被点过的那个播放器」才响应 H this.armed = null; // 点击时解析出来的 video / iframe this.clickPoint = null; // 最近一次在本文档内点击的视口坐标 this.frameArmed = null; // 最近一次「从 iframe 内部点进来」的那个 iframe this.helpEl = null; this.onGlobalKey = this.onGlobalKey.bind(this); this.onOverlayKey = this.onOverlayKey.bind(this); this.onOverlayKeyUp = this.onOverlayKeyUp.bind(this); document.addEventListener('keydown', this.onGlobalKey, true); // 常驻:记录点击落点,用来判断「H 该放大哪一个」 document.addEventListener('pointerdown', (e) => this.onPointerDown(e), true); // 与 iframe 之间的协议: // 子 → 父:pointer(我这边被点了)、enlarge-frame(请放大我这个 iframe)、collapse(请求收起) // 父 → 子:activate(你自己接管按键吧)、deactivate(收起) window.addEventListener('message', (e) => { const data = e.data; if (!data || !data.__vfp) return; if (data.__vfp === 'collapse') { if (this.activeVideo) this.exit(); return; } if (data.__vfp === 'pointer') { if (this.activeVideo) return; for (const frame of document.querySelectorAll('iframe')) { if (frame.contentWindow === e.source) { this.armFrame(frame); return; } } return; } if (data.__vfp === 'activate') { const video = this.pickVideo(); if (video && !this.activeVideo) this.beginRemote(video); return; } if (data.__vfp === 'deactivate') { this.endRemote(); return; } if (data.__vfp === 'enlarge-frame') { if (this.activeVideo) return; for (const frame of document.querySelectorAll('iframe')) { if (frame.contentWindow === e.source) { this.enter(frame); return; } } } }); this.ensureStyles(); } /* ---------- iframe 被放大后的「遥控」模式 ---------- */ // 放大的是父页面里的 iframe 元素,但按键事件只在焦点所在的文档里派发。 // 焦点在 iframe 里时,只能由 iframe 里的实例自己处理按键。 beginRemote(video) { if (this.remote || this.activeVideo) return; this.remote = true; this.mode = 'video'; this.activeVideo = video; this.rate = clamp(parseFloat(video.playbackRate) || 1, RATE_MIN, RATE_MAX); const hint = document.createElement('div'); hint.className = 'vfp-hint vfp-hint-fixed'; document.body.appendChild(hint); this.ui = { root: null, bar: null, playBtn: null, timeEl: null, progress: null, track: null, fill: null, rateBtns: [], hint }; this.on(document, 'keydown', this.onOverlayKey, true); this.on(document, 'keyup', this.onOverlayKeyUp, true); this.on(window, 'blur', () => { this.clearHoldTimer(); this.pendingSeek = null; this.stopBoost(); }); this.remoteTimer = setInterval(() => { if (!video.isConnected) this.endRemote(); }, 1000); this.showHint('已铺满窗口 · 空格播放 · ←/→ 跳转 · H 退出', 2600); } endRemote() { if (!this.remote) return; this.remote = false; this.stopBoost(); this.clearHoldTimer(); this.pendingSeek = null; this.offAll(); clearInterval(this.remoteTimer); clearTimeout(this.hintTimer); this.remoteTimer = 0; this.hintTimer = 0; if (this.ui && this.ui.hint) this.ui.hint.remove(); this.ui = null; this.activeVideo = null; } requestCollapse() { this.endRemote(); try { window.parent.postMessage({ __vfp: 'collapse' }, '*'); } catch (e) { /* ignore */ } } /* ---------- 点击聚焦:H 只对点过的那个播放器生效 ---------- */ onPointerDown(e) { if (this.activeVideo) return; // 网页全屏状态下的点击归遮罩自己管 const el = realTarget(e); if (!el || el.nodeType !== 1) return; if (typeof el.closest === 'function' && el.closest('.vfp-root,.vfp-toast,.vfp-help')) return; // 能在本文档收到点击,说明这一下不在 iframe 里面,清掉「来自 iframe」的记忆 this.frameArmed = null; this.clickPoint = { x: e.clientX, y: e.clientY }; // 顺带告诉父页面「点的是我这一块」:父页面收不到 iframe 内部的点击事件 if (window.top !== window.self) { try { window.parent.postMessage({ __vfp: 'pointer' }, '*'); } catch (err) { /* ignore */ } } this.armed = this.hitAt(e.clientX, e.clientY); } // 只看本文档的 video:iframe 里的元素用的是另一套视口坐标,混在一起会比错 localVideos() { const out = []; for (const v of document.querySelectorAll('video')) out.push(v); if (out.length) return out; const walk = (root, depth) => { if (depth > 3) return; let els; try { els = root.querySelectorAll('*'); } catch (e) { return; } for (const el of els) { if (!el.shadowRoot) continue; for (const v of el.shadowRoot.querySelectorAll('video')) out.push(v); walk(el.shadowRoot, depth + 1); } }; walk(document, 0); return out; } // 视口坐标 (x, y) 落在哪个播放器上:面积最大的那个 video 优先,其次 iframe hitAt(x, y) { const videos = []; for (const v of this.localVideos()) { if (!v.isConnected) continue; const r = v.getBoundingClientRect(); if (r.width <= 0 || r.height <= 0) continue; if (x < r.left || x > r.right || y < r.top || y > r.bottom) continue; const cs = getComputedStyle(v); if (cs.display === 'none' || cs.visibility === 'hidden' || cs.opacity === '0') continue; videos.push({ el: v, area: r.width * r.height }); } if (videos.length) { videos.sort((a, b) => b.area - a.area); return videos[0].el; } const frames = []; for (const f of document.querySelectorAll('iframe')) { const r = f.getBoundingClientRect(); if (r.width < 80 || r.height < 60) continue; if (x < r.left || x > r.right || y < r.top || y > r.bottom) continue; const cs = getComputedStyle(f); if (cs.display === 'none' || cs.visibility === 'hidden') continue; frames.push({ el: f, area: r.width * r.height }); } if (frames.length) { frames.sort((a, b) => b.area - a.area); return frames[0].el; } return null; } armFrame(frame) { if (this.activeVideo || !frame) return; this.frameArmed = frame; this.armed = frame; this.clickPoint = null; } // 当前该放大的目标:iframe 内部点过 → 就是那个 iframe;否则是点过的 video armedTarget() { const ok = (el) => { if (!el || !el.isConnected) return false; const r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0; }; if (this.frameArmed) { if (ok(this.frameArmed)) return this.frameArmed; this.frameArmed = null; } if (ok(this.armed)) return this.armed; // 点过之后页面重排、元素被换掉时,用落点重新找一次 if (this.clickPoint) { const hit = this.hitAt(this.clickPoint.x, this.clickPoint.y); if (hit) { this.armed = hit; return hit; } } return null; } // 没点过就按 H:先提醒,别去猜 nudgeToClick() { const videos = this.localVideos().filter((v) => v.isConnected); const frames = document.querySelectorAll('iframe').length; if (!videos.length && !frames) { this.reportNothing(); return; } this.toast('先点一下要放大的播放器,H 只对点过的那个生效'); } /* ---------- 快捷键面板 ---------- */ toggleHelp() { if (this.helpEl) { this.helpEl.remove(); this.helpEl = null; return; } const rows = [ ['H', '进入 / 退出网页全屏(先点一下播放器)'], ['空格 / K', '播放 / 暂停'], ['← / →', '后退 / 前进 5 秒'], ['Shift + ← / →', '后退 / 前进 10 秒'], ['按住 ← / →', '临时 2x,松开恢复原倍速'], ['C', '加快一档:1 → 1.25 → 1.5 → 2 → 3 → 5 → 9 → 16'], ['X', '放慢一档:1 → 0.75 → 0.5 → 0.4 → 0.3 → 0.2 → 0.1'], ['Shift + C / X', '精细微调 ±0.1x'], ['Z', '恢复 1x'], ['↑ / ↓', '音量 ±10%'], ['M', '静音开关'], ['F', '浏览器原生全屏'], ['Esc', '退出'], ['?', '显示 / 关闭这张表'], ['底部按钮', '倍速 / 音量 / 全屏 / 退出(点开是弹层)'] ]; const box = document.createElement('div'); box.className = 'vfp-help'; const title = document.createElement('h4'); title.textContent = '视频网页全屏播放 · 快捷键'; const dl = document.createElement('dl'); for (const [key, text] of rows) { const dt = document.createElement('dt'); dt.textContent = key; const dd = document.createElement('dd'); dd.textContent = text; dl.append(dt, dd); } box.append(title, dl); document.body.appendChild(box); this.helpEl = box; setTimeout(() => { if (this.helpEl === box) { box.remove(); this.helpEl = null; } }, 8000); } /* ---------- 基础工具 ---------- */ on(target, type, fn, opts) { target.addEventListener(type, fn, opts); this.listeners.push([target, type, fn, opts]); } offAll() { for (const [target, type, fn, opts] of this.listeners) { try { target.removeEventListener(type, fn, opts); } catch (e) { /* ignore */ } } this.listeners = []; } /* ---------- 样式与入口按钮 ---------- */ ensureStyles() { if (document.getElementById('vfp-style')) return; const style = document.createElement('style'); style.id = 'vfp-style'; style.textContent = ` .vfp-root { position: fixed; inset: 0; background: #000; z-index: ${Z_ROOT}; overflow: hidden; font: 500 13px/1.4 system-ui, -apple-system, "Segoe UI", "Microsoft YaHei", sans-serif; -webkit-user-select: none; user-select: none; } .vfp-root.vfp-idle, .vfp-root.vfp-idle video { cursor: none !important; } .vfp-root.vfp-frame { background: transparent; } .vfp-backdrop { position: fixed; inset: 0; background: #000; z-index: 2147483644; } .vfp-bar { position: absolute; left: 0; right: 0; bottom: 0; z-index: 2; display: flex; align-items: center; gap: 10px; padding: 26px 16px 12px; background: linear-gradient(to top, rgba(0, 0, 0, .78), rgba(0, 0, 0, 0)); opacity: 0; transform: translateY(8px); transition: opacity .22s ease, transform .22s ease; pointer-events: none; } .vfp-bar.vfp-show { opacity: 1; transform: none; pointer-events: auto; } .vfp-btn { appearance: none; border: 0; background: rgba(255, 255, 255, .16); color: #fff; border-radius: 6px; padding: 7px 9px; font: inherit; line-height: 1; min-width: 32px; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; transition: background-color .15s ease; } .vfp-btn:hover { background: rgba(255, 255, 255, .3); } .vfp-btn.vfp-on { background: #ff2d55; } .vfp-time { font-variant-numeric: tabular-nums; white-space: nowrap; opacity: .92; } .vfp-progress { position: relative; flex: 1 1 auto; height: 16px; display: flex; align-items: center; cursor: pointer; touch-action: none; } .vfp-progress.vfp-static { cursor: default; } .vfp-track { position: relative; width: 100%; height: 4px; background: rgba(255, 255, 255, .32); border-radius: 2px; overflow: hidden; } .vfp-fill { position: absolute; left: 0; top: 0; height: 100%; width: 0; background: #ff2d55; } .vfp-pop .vfp-btn { padding: 7px 10px; font-size: 12px; min-width: 56px; } .vfp-hint { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); z-index: 3; padding: 10px 20px; border-radius: 999px; background: rgba(0, 0, 0, .72); color: #fff; font-size: 16px; pointer-events: none; opacity: 0; transition: opacity .18s ease; } .vfp-hint.vfp-show { opacity: 1; } .vfp-hint-fixed { position: fixed; z-index: 2147483647; } .vfp-badges { position: absolute; right: 18px; top: 16px; z-index: 3; display: flex; align-items: center; gap: 6px; pointer-events: none; } .vfp-rate-badge, .vfp-mute-badge { padding: 4px 9px; border-radius: 6px; background: rgba(0, 0, 0, .55); color: #fff; font: 600 12px/1.2 system-ui, -apple-system, "Segoe UI", "Microsoft YaHei", sans-serif; font-variant-numeric: tabular-nums; opacity: 0; transition: opacity .2s ease; pointer-events: none; } .vfp-rate-badge.vfp-show, .vfp-mute-badge.vfp-show { opacity: .88; } .vfp-drop { position: relative; display: flex; align-items: center; } .vfp-pop { position: absolute; right: 0; bottom: calc(100% + 10px); z-index: 4; display: none; padding: 8px; border-radius: 8px; background: rgba(18, 18, 20, .96); box-shadow: 0 12px 32px rgba(0, 0, 0, .55); white-space: nowrap; } .vfp-pop.vfp-open { display: flex; } .vfp-pop.vfp-col { flex-direction: column; gap: 4px; } .vfp-pop .vfp-btn { justify-content: flex-start; } .vfp-vol-row { display: flex; align-items: center; gap: 10px; padding: 2px 4px; } .vfp-vol-row input[type="range"] { width: 132px; accent-color: #ff2d55; cursor: pointer; } .vfp-vol-num { min-width: 40px; text-align: right; font-variant-numeric: tabular-nums; opacity: .9; } .vfp-help { position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%); z-index: 2147483647; min-width: 320px; max-width: 86vw; padding: 16px 20px 14px; border-radius: 12px; background: rgba(16, 16, 18, .95); color: #fff; font: 500 13px/1.65 system-ui, -apple-system, "Segoe UI", "Microsoft YaHei", sans-serif; box-shadow: 0 16px 48px rgba(0, 0, 0, .55); pointer-events: none; } .vfp-help h4 { margin: 0 0 10px; font-size: 14px; font-weight: 600; opacity: .95; } .vfp-help dl { display: grid; grid-template-columns: auto 1fr; gap: 4px 16px; margin: 0; } .vfp-help dt { color: #7fb0ff; font-weight: 600; white-space: nowrap; font-variant-numeric: tabular-nums; } .vfp-help dd { margin: 0; opacity: .88; } .vfp-toast { position: fixed; left: 50%; bottom: 40px; transform: translateX(-50%); z-index: 2147483647; max-width: 80vw; padding: 10px 16px; border-radius: 8px; background: rgba(0, 0, 0, .82); color: #fff; font: 500 13px/1.5 system-ui, -apple-system, "Segoe UI", "Microsoft YaHei", sans-serif; pointer-events: none; } @media (max-width: 720px) { .vfp-time { display: none; } } `; (document.head || document.documentElement).appendChild(style); } /* ---------- 选择目标视频 ---------- */ // 本页 / 同源 iframe / shadow DOM 里的所有 video allVideos() { const out = []; const seen = new Set(); const add = (v) => { if (v && !seen.has(v)) { seen.add(v); out.push(v); } }; for (const v of document.querySelectorAll('video')) add(v); if (out.length) return out; // 同源 iframe;跨域会被浏览器拦住,try 掉即可 for (const frame of document.querySelectorAll('iframe')) { try { const doc = frame.contentDocument; if (!doc) continue; for (const v of doc.querySelectorAll('video')) add(v); } catch (e) { /* 跨域 iframe */ } } if (out.length) return out; // 打开状态的 shadow root:遍历较贵,只在前两种都没找到时做 const walk = (root, depth) => { if (depth > 3) return; let els; try { els = root.querySelectorAll('*'); } catch (e) { return; } for (const el of els) { if (!el.shadowRoot) continue; for (const v of el.shadowRoot.querySelectorAll('video')) add(v); walk(el.shadowRoot, depth + 1); } }; walk(document, 0); return out; } // 布局尺寸为 0 时退回媒体自身分辨率:有些站点点了播放才把 video 显示出来 measure(video) { const rect = video.getBoundingClientRect(); return { rect, w: rect.width || video.videoWidth || 0, h: rect.height || video.videoHeight || 0 }; } pickVideo() { const videos = this.allVideos(); const vw = window.innerWidth || 1; const vh = window.innerHeight || 1; const hovered = document.querySelector('video:hover'); let best = null; let bestScore = 0; let loose = null; let looseScore = 0; for (const video of videos) { if (!video.isConnected) continue; const { rect, w, h } = this.measure(video); if (!w || !h) continue; let score = w * h; const inView = rect.right > 0 && rect.bottom > 0 && rect.left < vw && rect.top < vh; if (inView) score *= 2; if (!video.paused) score *= 2; if (video === this.lastVideo) score *= 1.2; if (video === hovered) score *= 3; const cs = getComputedStyle(video); const visible = cs.visibility !== 'hidden' && cs.opacity !== '0'; const big = w >= MIN_W && h >= MIN_H; const laidOut = cs.display !== 'none' && rect.width > 0 && rect.height > 0; if (visible && big && laidOut) { if (score > bestScore) { best = video; bestScore = score; } } else if (Math.min(w, h) >= 32 && score > looseScore) { // 太小或被隐藏的,留作兜底:用户明确按了 H,就给它一次机会 loose = video; looseScore = score; } } return best || loose; } /* ---------- 进出网页全屏 ---------- */ enter(target) { if (this.activeVideo || !target || !document.body) return; const isFrame = target.tagName === 'IFRAME'; if (!isFrame && window.top !== window.self) { // 同源 iframe:交给顶层页面处理,得到真正的网页全屏 try { const topApi = window.top.__vfp; if (topApi && topApi !== this && typeof topApi.enter === 'function') { topApi.enter(target); return; } } catch (e) { /* 跨域,取不到 */ } // 跨域 iframe:请父页面把「这个 iframe 元素」放大,而不是把浏览器切成系统全屏 try { window.parent.postMessage({ __vfp: 'enlarge-frame' }, '*'); return; } catch (e) { /* ignore */ } } this.mode = isFrame ? 'frame' : 'video'; this.lastVideo = target; this.state = { video: target, styleAttr: target.getAttribute('style'), parent: target.parentNode, next: target.nextSibling, scrollX: window.scrollX, scrollY: window.scrollY, htmlOverflow: document.documentElement.style.overflow, bodyOverflow: document.body.style.overflow }; this.activeVideo = target; this.dragging = false; const root = document.createElement('div'); root.className = isFrame ? 'vfp-root vfp-frame' : 'vfp-root'; // iframe 只改样式(不进 DOM),video 则搬进遮罩 const styleMap = isFrame ? FRAME_STYLE : VIDEO_STYLE; for (const [prop, value] of Object.entries(styleMap)) { target.style.setProperty(prop, value, 'important'); } if (isFrame) { const backdrop = document.createElement('div'); backdrop.className = 'vfp-backdrop'; this.backdrop = backdrop; document.body.appendChild(backdrop); } else { root.appendChild(target); } const bar = document.createElement('div'); bar.className = 'vfp-bar'; const fsBtn = makeButton('⛶', '浏览器全屏(F)'); const exitBtn = makeButton('✕', '退出网页全屏(Esc / H)'); let playBtn = null; let timeEl = null; let progress = null; let track = null; let fill = null; let rateBtn = null; let ratePop = null; let volBtn = null; let volPop = null; let volInput = null; let volNum = null; let muteBtn = null; const rateBtns = []; if (!isFrame) { playBtn = makeButton('▶', '播放 / 暂停(空格)'); timeEl = document.createElement('span'); timeEl.className = 'vfp-time'; timeEl.textContent = '0:00 / --:--'; progress = document.createElement('div'); progress.className = 'vfp-progress'; track = document.createElement('div'); track.className = 'vfp-track'; fill = document.createElement('div'); fill.className = 'vfp-fill'; track.appendChild(fill); progress.appendChild(track); // 倍速:一个按钮显示当前档位,点开才是预设列表 const rateWrap = document.createElement('div'); rateWrap.className = 'vfp-drop'; rateBtn = makeButton('1x', '倍速(C / X 换档,Shift 微调)'); rateBtn.classList.add('vfp-drop-btn'); ratePop = document.createElement('div'); ratePop.className = 'vfp-pop vfp-col'; for (const rate of RATE_PRESETS) { const btn = makeButton(`${rate}x`, `倍速 ${rate}x`); btn.dataset.rate = String(rate); ratePop.appendChild(btn); rateBtns.push(btn); } rateWrap.append(rateBtn, ratePop); // 音量:按钮 + 弹层(弹层里是静音键 + 滑杆) const volWrap = document.createElement('div'); volWrap.className = 'vfp-drop'; volBtn = makeButton('🔊', '音量(↑ / ↓ 调节,M 静音)'); volBtn.classList.add('vfp-drop-btn'); volPop = document.createElement('div'); volPop.className = 'vfp-pop'; const volRow = document.createElement('div'); volRow.className = 'vfp-vol-row'; muteBtn = makeButton('🔊', '静音开关(M)'); volInput = document.createElement('input'); volInput.type = 'range'; volInput.min = '0'; volInput.max = '100'; volInput.step = '1'; volInput.value = '100'; volInput.title = '音量'; volNum = document.createElement('span'); volNum.className = 'vfp-vol-num'; volNum.textContent = '100%'; volRow.append(muteBtn, volInput, volNum); volPop.appendChild(volRow); volWrap.append(volBtn, volPop); bar.append(playBtn, timeEl, progress, rateWrap, volWrap); } bar.append(fsBtn, exitBtn); root.appendChild(bar); const hint = document.createElement('div'); hint.className = 'vfp-hint'; root.appendChild(hint); let rateBadge = null; let muteBadge = null; if (!isFrame) { const badges = document.createElement('div'); badges.className = 'vfp-badges'; rateBadge = document.createElement('div'); rateBadge.className = 'vfp-rate-badge'; muteBadge = document.createElement('div'); muteBadge.className = 'vfp-mute-badge'; muteBadge.textContent = '🔇 静音'; badges.append(rateBadge, muteBadge); root.appendChild(badges); } this.ui = { root, bar, playBtn, timeEl, progress, track, fill, rateBtns, hint, rateBadge, muteBadge, rateBtn, ratePop, volBtn, volPop, volInput, volNum, muteBtn }; document.body.appendChild(root); document.documentElement.style.overflow = 'hidden'; document.body.style.overflow = 'hidden'; if (isFrame) { // 焦点在 iframe 里时按键不会派发到父页面,让 iframe 里的实例自己接管 try { target.contentWindow.postMessage({ __vfp: 'activate' }, '*'); } catch (e) { /* ignore */ } } else { // 以元素当前速度为准启动(本次不再记忆倍速) this.rate = clamp(parseFloat(target.playbackRate) || 1, RATE_MIN, RATE_MAX); } const reveal = () => this.reveal(); this.on(root, 'pointermove', reveal); this.on(root, 'pointerdown', reveal); this.on(root, 'pointerleave', () => { if (!this.dragging) this.hideBar(); }); this.on(exitBtn, 'click', (e) => { e.stopPropagation(); this.exit(); }); this.on(fsBtn, 'click', (e) => { e.stopPropagation(); this.toggleNativeFullscreen(); }); if (!isFrame) { this.on(target, 'click', (e) => { e.preventDefault(); e.stopPropagation(); this.togglePlay(); }); this.on(playBtn, 'click', (e) => { e.stopPropagation(); this.togglePlay(); }); // 倍速:点按钮开弹层,选一档后自动收起 this.on(rateBtn, 'click', (e) => { e.stopPropagation(); this.togglePop(ratePop); }); for (const btn of rateBtns) { this.on(btn, 'click', (e) => { e.stopPropagation(); this.setRate(parseFloat(btn.dataset.rate), true); this.closePops(); }); } // 音量:点按钮开弹层,弹层里静音键 + 滑杆 this.on(volBtn, 'click', (e) => { e.stopPropagation(); this.togglePop(volPop); }); this.on(muteBtn, 'click', (e) => { e.stopPropagation(); this.toggleMute(); }); this.on(volInput, 'input', (e) => { e.stopPropagation(); this.setVolume(parseFloat(volInput.value) / 100, true); }); this.on(volInput, 'change', (e) => { e.stopPropagation(); }); // 点界面其他位置收起弹层(弹层和它自己的按钮除外) this.on(root, 'pointerdown', (e) => { const el = realTarget(e); if (!el || el.nodeType !== 1) return; if (typeof el.closest === 'function' && el.closest('.vfp-pop,.vfp-drop-btn')) return; this.closePops(); }); const seekTo = (clientX) => { const duration = target.duration; if (!isFinite(duration) || duration <= 0) return; const rect = track.getBoundingClientRect(); if (!rect.width) return; target.currentTime = duration * clamp((clientX - rect.left) / rect.width, 0, 1); this.render(); }; this.on(progress, 'pointerdown', (e) => { if (e.button !== 0) return; e.preventDefault(); e.stopPropagation(); this.dragging = true; try { progress.setPointerCapture(e.pointerId); } catch (err) { /* ignore */ } seekTo(e.clientX); }); this.on(progress, 'pointermove', (e) => { if (this.dragging) seekTo(e.clientX); }); const endDrag = (e) => { this.dragging = false; try { progress.releasePointerCapture(e.pointerId); } catch (err) { /* ignore */ } this.reveal(); }; this.on(progress, 'pointerup', endDrag); this.on(progress, 'pointercancel', endDrag); for (const type of ['timeupdate', 'durationchange', 'loadedmetadata', 'play', 'pause', 'volumechange', 'ratechange', 'ended']) { this.on(target, type, () => this.render()); } // 站点自己改倍速时(比如播放器自带的速度菜单),让内部档位跟上, // 否则再按 C/X 会从旧档重新开始,反而把速度改回去 this.on(target, 'ratechange', () => { if (this.boosting) return; const now = target.playbackRate; if (!isFinite(now) || now <= 0) return; if (now < RATE_MIN - 1e-6 || now > RATE_MAX + 1e-6) return; if (Math.abs(now - this.rate) < 0.01) return; this.rate = Math.round(now * 100) / 100; this.render(); }); // 有些播放器在开播 / 缓冲后会把速率重置回 1,按用户选择重新压回去(长按加速期间除外) this.on(target, 'play', () => { if (this.boosting) return; if (this.rate && Math.abs(target.playbackRate - this.rate) > 0.01) { try { target.playbackRate = this.rate; } catch (e) { /* ignore */ } } }); } this.on(document, 'keydown', this.onOverlayKey, true); this.on(document, 'keyup', this.onOverlayKeyUp, true); this.on(window, 'blur', () => { this.clearHoldTimer(); this.pendingSeek = null; this.stopBoost(); }); // 站点若把节点摘掉(SPA 切路由等),自动退出 this.watchTimer = setInterval(() => { if (!target.isConnected) this.exit(); }, 1000); if (!isFrame) { // 进入后校验:站点可能把视频挪回去,或者选中的根本不是播放器 this.recheckTimer = setTimeout(() => this.verifyEntry(target, root), 500); } this.render(); this.reveal(); } verifyEntry(video, root) { this.recheckTimer = 0; if (!this.activeVideo) return; const info = { src: (video.currentSrc || video.src || '').slice(0, 80), 分辨率: [video.videoWidth, video.videoHeight], 还在遮罩里: video.parentElement === root, 是顶层页面: window.top === window.self }; console.info('[vfp] 进入网页全屏', info); if (video.parentElement !== root) { this.showHint('这个播放器把视频挪回去了,暂不支持', 3000); } else if (!video.videoWidth) { this.showHint('选中的视频没有画面数据,可能不是真正的播放器', 3000); } } exit() { const state = this.state; if (!state) return; const target = state.video; const wasFrame = this.mode === 'frame'; // 长按加速中退出:先恢复用户倍速,再拆界面 this.stopBoost(); this.clearHoldTimer(); this.pendingSeek = null; this.offAll(); clearTimeout(this.hideTimer); clearTimeout(this.hintTimer); clearTimeout(this.recheckTimer); clearInterval(this.watchTimer); this.hideTimer = 0; this.hintTimer = 0; this.recheckTimer = 0; this.watchTimer = 0; this.dragging = false; this.mode = 'video'; if (document.fullscreenElement) { const done = document.exitFullscreen && document.exitFullscreen(); if (done && done.catch) done.catch(() => {}); } if (wasFrame) { try { target.contentWindow.postMessage({ __vfp: 'deactivate' }, '*'); } catch (e) { /* ignore */ } } if (this.ui && this.ui.root) this.ui.root.remove(); this.ui = null; if (this.backdrop) { this.backdrop.remove(); this.backdrop = null; } // 精确还原内联样式 if (state.styleAttr === null) target.removeAttribute('style'); else target.setAttribute('style', state.styleAttr); // 放回原位置(iframe 从没搬过节点,不用管),节点关系已失效时降级追加 if (!wasFrame) { if (state.parent && state.parent.isConnected) { const before = state.next && state.next.parentNode === state.parent ? state.next : null; try { state.parent.insertBefore(target, before); } catch (e) { try { state.parent.appendChild(target); } catch (err) { /* ignore */ } } } else if (state.next && state.next.parentNode) { try { state.next.parentNode.insertBefore(target, state.next); } catch (e) { /* ignore */ } } } document.documentElement.style.overflow = state.htmlOverflow; document.body.style.overflow = state.bodyOverflow; requestAnimationFrame(() => { window.scrollTo(state.scrollX || 0, state.scrollY || 0); }); target.dispatchEvent(new CustomEvent('exitfullpage')); this.state = null; this.activeVideo = null; } /* ---------- 键盘 ---------- */ onGlobalKey(e) { if (this.remote) return; if (e.ctrlKey || e.altKey || e.metaKey) return; if (isEditable(realTarget(e))) return; // 注意:? 快捷键表只在网页全屏状态下响应(由 onOverlayKey 负责), // 普通浏览时不拦截,免得抢站点自己的快捷键 if (e.code !== 'KeyH') return; if (this.activeVideo) { e.preventDefault(); this.exit(); return; } // 只放大「用户点过的那个」:多视频页面不会点错,也不靠猜 const target = this.armedTarget(); if (!target) { this.nudgeToClick(); return; } e.preventDefault(); this.enter(target); } // 按了 H 却没有视频时的处理:先看有没有「鼠标正指着的 iframe 播放器」 reportNothing() { const frame = this.pickFrame(); if (frame) { this.enter(frame); return; } let text = '没找到可全屏的视频'; try { const video = document.querySelector('video'); const audio = document.querySelector('audio'); if (!video && audio) { text = '这个页面只有