1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
| // ==UserScript== // @name B站网页全屏模式显示评论区(播放器下方按钮点击启用) // @namespace https://magiku.github.io/ // @version 2.0 // @description 网页全屏/完全全屏时在控制栏添加评论按钮,点击后视频左移、评论区嵌入播放器右侧;切换视频/分集评论自动跟随,无需整页刷新 // @match https://www.bilibili.com/video/* // @author magiku // @grant none // @license MIT // @icon https://www.bilibili.com/favicon.ico // ==/UserScript==
(function() { 'use strict'; const CONFIG = { playerSelector: '#bilibili-player', videoWrapSelector: '.bpx-player-video-wrap', commentSelector: '#commentapp', controlRightSelector: '.bpx-player-control-bottom-right', //评论区占比大小(默认值;拖拽调整后会记住新的占比) commentWidth: '35%', //视频与评论区之间分隔条的宽度(px) resizerWidth: 6, //拖拽可调整的评论区占比范围 minCommentRatio: 0.15, maxCommentRatio: 0.7, //是否记住拖拽调整后的占比 rememberWidth: true, ratioStorageKey: 'bili-side-comment-ratio', //支持的全屏模式:web=网页全屏,full=完全全屏(浏览器全屏) fullscreenScreens: ['web', 'full'], pollInterval: 500, //B站评论组件被移动时会抛出一个无信息的 Promise 拒绝(组件自身缺陷)。 //该噪声只出现在我们搬运评论区的前后,这里做"时间窗内 + reason 为空"的定向静默; //如不希望改动页面行为,可置为 false。 suppressMoveNoise: true, moveNoiseWindow: 3000, }; // B站评论组件(bili-comments)在自身被移动时会触发 disconnectedCallback, // 其中以非法参数调用了 IntersectionObserver.unobserve 并抛错,污染控制台。 // 这里做最小防御:参数不是 Element 时忽略(语义上等同于"无需取消观察"), // 不改变任何合法调用的行为。 (function guardIntersectionObserver() { if (!window.IntersectionObserver || !window.IntersectionObserver.prototype) return; const proto = window.IntersectionObserver.prototype; const originalUnobserve = proto.unobserve; proto.unobserve = function(target) { if (!(target instanceof Element)) return; return originalUnobserve.call(this, target); }; })(); let isFullscreen = false; let activeScreen = null; let leaveFullscreenTimer = null; let isEmbedded = false; let toggleBtn = null; let commentContainer = null; let resizer = null; let embeddedPrimaryArea = null; let currentRatio = null; let dragging = false; let dragOffset = 0; let originalParent = null; let originalNextSibling = null; let originalStyles = []; let embeddedRoot = null; let embeddedCommentApp = null; let pollTimer = null; let controlWaitObserver = null; let screenObserver = null; let screenObserverTarget = null; let lastMoveAt = 0; function markCommentMove() { lastMoveAt = Date.now(); } function installMoveNoiseGuard() { if (!CONFIG.suppressMoveNoise) return; window.addEventListener('unhandledrejection', (ev) => { if (ev.reason === undefined && Date.now() - lastMoveAt < CONFIG.moveNoiseWindow) { ev.preventDefault(); } }); } function getPlayer() { return document.querySelector(CONFIG.playerSelector); } function getVideoWrap() { let el = document.querySelector(CONFIG.videoWrapSelector); if (!el) { const player = getPlayer(); if (player) { el = player.querySelector('.bpx-player-video-wrap') || player.querySelector('.bilibili-player-video-wrap'); } } return el; } function getCommentApp() { return document.querySelector(CONFIG.commentSelector); } function getControlRight() { return document.querySelector(CONFIG.controlRightSelector); } function getScreenMode() { const player = getPlayer(); const container = player && player.querySelector('.bpx-player-container'); return container ? container.getAttribute('data-screen') : null; } function detectFullscreen() { return CONFIG.fullscreenScreens.indexOf(getScreenMode()) !== -1; } function getLayoutRoot() { // bpx-player-container 是完全全屏时的 fullscreenElement;网页全屏也用同一层, // 这样侧栏在两种模式间切换时始终位于播放器容器内部。 const player = getPlayer(); return (player && player.querySelector('.bpx-player-container')) || player; } function rememberStyle(element, properties) { if (!element || originalStyles.some(item => item.element === element)) return; const values = {}; for (const property of properties) values[property] = element.style[property]; originalStyles.push({ element, values }); } function restoreStyles() { for (const item of originalStyles) { for (const [property, value] of Object.entries(item.values)) item.element.style[property] = value; } originalStyles = []; } // ========== 视频/评论区占比:计算与持久化 ========== function clampRatio(ratio) { return Math.min(CONFIG.maxCommentRatio, Math.max(CONFIG.minCommentRatio, ratio)); } function defaultRatio() { const n = parseFloat(CONFIG.commentWidth); return clampRatio(isNaN(n) ? 0.35 : n / 100); } function loadRatio() { if (CONFIG.rememberWidth) { try { const v = parseFloat(localStorage.getItem(CONFIG.ratioStorageKey)); if (!isNaN(v) && v > 0 && v < 1) return clampRatio(v); } catch (e) {} } return defaultRatio(); } function saveRatio(ratio) { if (!CONFIG.rememberWidth || !ratio) return; try { localStorage.setItem(CONFIG.ratioStorageKey, String(ratio)); } catch (e) {} } // 用 calc 让两侧宽度之和恰好等于"容器宽度 - 分隔条宽度",百分比会随窗口缩放自动跟随 function applyRatio(ratio) { currentRatio = ratio; const rest = Number((1 - ratio).toFixed(6)); const share = Number(ratio.toFixed(6)); const basis = (v) => `calc((100% - ${CONFIG.resizerWidth}px) * ${v})`; if (embeddedPrimaryArea) { embeddedPrimaryArea.style.flex = '0 0 ' + basis(rest); embeddedPrimaryArea.style.width = basis(rest); } if (commentContainer) { commentContainer.style.flex = '0 0 ' + basis(share); commentContainer.style.width = basis(share); } } // 分隔条:拖拽改变视频与评论区的屏占比 function createResizer(root) { const bar = document.createElement('div'); bar.id = 'embedded-comment-resizer'; bar.setAttribute('role', 'separator'); bar.setAttribute('aria-label', '拖拽调整评论区宽度'); // 分隔条本体只用"评论面板同色"打底(--bg1:浅色为白、深色自动跟随), // 一是挡住视频元素从下方透出,二是让分隔区在默认状态下与评论区融为一体、 // 看不出多余的色带。宽度不写死,统一由 applyRatio 用 flex-basis 控制。 // 注意 justify-content 用 flex-start:握把必须贴住分隔条的左边缘, // 也就是紧贴视频画面,这样从左到右才是"黑视频 → 灰握把 → 白评论"的自然过渡; // 若居中,握把左侧会夹出一条 2px 白缝,在黑背景上很显眼。 bar.style.cssText = ` flex: 0 0 ${CONFIG.resizerWidth}px; width: ${CONFIG.resizerWidth}px; height: 100%; cursor: col-resize; display: flex; align-items: center; justify-content: flex-start; background: var(--bg1, #fff); user-select: none; touch-action: none; `; // 握把:一条贯穿顶到底的 2px 竖线,默认透明不显示,悬停/拖拽时才淡入。 const grip = document.createElement('div'); grip.style.cssText = ` width: 2px; height: 100%; border-radius: 0; background: rgba(128,128,128,0.85); pointer-events: none; opacity: 0; transition: opacity .15s; `; bar.appendChild(grip); let hovering = false; const setGrip = (active) => { grip.style.opacity = active ? '1' : '0'; }; bar.addEventListener('mouseenter', () => { hovering = true; setGrip(true); }); bar.addEventListener('mouseleave', () => { hovering = false; if (!dragging) setGrip(false); }); bar.addEventListener('pointerdown', (e) => { e.preventDefault(); e.stopPropagation(); dragging = true; dragOffset = e.clientX - bar.getBoundingClientRect().left; setGrip(true); try { bar.setPointerCapture(e.pointerId); } catch (err) {} }); bar.addEventListener('pointermove', (e) => { if (!dragging) return; e.preventDefault(); e.stopPropagation(); const rootRect = root.getBoundingClientRect(); const total = rootRect.width - CONFIG.resizerWidth; if (total <= 0) return; const dividerLeft = e.clientX - dragOffset; applyRatio(clampRatio((rootRect.right - dividerLeft - CONFIG.resizerWidth) / total)); }); const endDrag = (e) => { if (!dragging) return; dragging = false; try { bar.releasePointerCapture(e.pointerId); } catch (err) {} saveRatio(currentRatio); setGrip(hovering); }; bar.addEventListener('pointerup', endDrag); bar.addEventListener('pointercancel', endDrag); return bar; } function removeEmbeddedNodes() { if (commentContainer && commentContainer.parentNode) commentContainer.remove(); if (resizer && resizer.parentNode) resizer.remove(); } function getCommentComponent() { const app = getCommentApp(); return (app && app.querySelector('bili-comments')) || document.querySelector('bili-comments'); } function reloadComments(commentApp) { try { const biliComments = commentApp.querySelector('bili-comments'); if (biliComments) { const lazy = biliComments.getAttribute('lazy-load'); biliComments.removeAttribute('lazy-load'); void biliComments.offsetHeight; biliComments.setAttribute('lazy-load', lazy || 'true'); if (typeof biliComments.reload === 'function') { biliComments.reload(); } } else { window.dispatchEvent(new Event('resize')); } } catch (e) {} } function cleanup() { isEmbedded = false; commentContainer = null; resizer = null; embeddedPrimaryArea = null; originalParent = null; originalNextSibling = null; originalStyles = []; embeddedRoot = null; embeddedCommentApp = null; } function forceCleanupEmbed() { removeEmbeddedNodes(); markCommentMove(); restoreStyles(); cleanup(); } function doEmbed(player, videoWrap, commentApp) { try { const root = getLayoutRoot(); const primaryArea = root && root.querySelector('.bpx-player-primary-area'); if (!player || !videoWrap || !commentApp || !root || !primaryArea) return;
if (isEmbedded && (embeddedCommentApp !== commentApp || embeddedRoot !== root)) { removeEmbeddedNodes(); restoreStyles(); cleanup(); } if (isEmbedded) return;
originalParent = commentApp.parentNode; originalNextSibling = commentApp.nextSibling; embeddedRoot = root; embeddedPrimaryArea = primaryArea; currentRatio = loadRatio();
// 保存播放器原样式,只改当前支持的全屏模式所需属性。 rememberStyle(root, ['display', 'flexDirection', 'alignItems']); rememberStyle(primaryArea, ['width', 'flex', 'minWidth']); rememberStyle(videoWrap, ['width', 'flex']);
root.style.display = 'flex'; root.style.flexDirection = 'row'; root.style.alignItems = 'stretch'; primaryArea.style.minWidth = '0'; videoWrap.style.width = '100%';
commentContainer = document.createElement('div'); commentContainer.id = 'embedded-comment-container'; // 只负责"占位 + 滚动",评论区内容一律沿用B站自带样式; // 背景取B站主题变量 --bg1(浅色为白、深色为深灰),取不到时退回白色。 // 宽度不在这里写死,统一由 applyRatio 设置,拖拽分隔条时实时改写。 commentContainer.style.cssText = ` height: 100%; min-width: 0; overflow-y: auto; overflow-x: hidden; background: var(--bg1, #fff); box-sizing: border-box; padding-top: 10px; `; // 播放器把"滚轮调音量"的监听挂在 document 和播放器根节点上(冒泡阶段), // 而侧栏就在播放器容器内部,滚轮冒泡上去会误触音量。这里就地截断, // 三种事件名都拦(wheel / mousewheel / DOMMouseScroll)。 ['wheel', 'mousewheel', 'DOMMouseScroll'].forEach((type) => { commentContainer.addEventListener(type, (e) => e.stopPropagation(), { passive: true }); });
resizer = createResizer(root); root.appendChild(resizer); root.appendChild(commentContainer); commentContainer.appendChild(commentApp); applyRatio(currentRatio); markCommentMove(); embeddedCommentApp = commentApp; isEmbedded = true; reloadComments(commentApp); } catch (e) {} }
function embedComments(force = false) { if (isEmbedded && !force) return;
const player = getPlayer(); const videoWrap = getVideoWrap(); let commentApp = getCommentApp();
if (!player || !videoWrap || !commentApp) { let attempts = 0; const maxAttempts = 20; const interval = setInterval(() => { attempts++; const p = getPlayer(); const vw = getVideoWrap(); const ca = getCommentApp(); if (p && vw && ca) { clearInterval(interval); doEmbed(p, vw, ca); } else if (attempts >= maxAttempts) { clearInterval(interval); } }, 500); return; } doEmbed(player, videoWrap, commentApp); } function restoreComments() { if (!isEmbedded) return; try { // 先把评论区搬回原位(脱离 commentContainer),再删除容器, // 否则删除容器会把评论区一起从 DOM 里带走。 const commentApp = embeddedCommentApp || getCommentApp(); if (commentApp) { if (originalParent && originalParent.isConnected) { if (originalNextSibling && originalNextSibling.parentNode === originalParent) { originalParent.insertBefore(commentApp, originalNextSibling); } else { originalParent.appendChild(commentApp); } } else { const fallback = document.querySelector('#viewbox') || document.body; fallback.appendChild(commentApp); } } removeEmbeddedNodes(); markCommentMove(); restoreStyles(); cleanup(); } catch (e) { forceCleanupEmbed(); } } function toggleEmbed() { try { if (isEmbedded) { restoreComments(); } else { embedComments(true); } } catch (e) {} } function createCommentButton() { if (toggleBtn) return; const controlRight = getControlRight(); if (!controlRight) return; toggleBtn = document.createElement('div'); toggleBtn.className = 'bpx-player-ctrl-btn bpx-player-ctrl-comment'; toggleBtn.setAttribute('role', 'button'); toggleBtn.setAttribute('aria-label', '内嵌评论'); toggleBtn.tabIndex = 0; toggleBtn.style.cssText = 'margin-top: 5px;'; const iconSpan = document.createElement('span'); iconSpan.className = 'bpx-player-ctrl-btn-icon'; iconSpan.innerHTML = `<svg fill="none" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M7 8H17M7 11H17M7 14H11M14.8284 18H19C20.1046 18 21 17.1046 21 16V6C21 4.89543 20.1046 4 19 4H5C3.89543 4 3 4.89543 3 6V16C3 17.1046 3.89543 18 5 18H8.18767C9.18859 18 10 18.8114 10 19.8123V19.8123C10 20.6196 10.9761 21.0239 11.5469 20.4531L13.4142 18.5858C13.7893 18.2107 14.298 18 14.8284 18Z" stroke="white" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"/></svg>`; toggleBtn.appendChild(iconSpan); toggleBtn.addEventListener('click', (e) => { e.stopPropagation(); toggleEmbed(); }); // 插到【字幕】与【音量】之间;字幕/音量任一缺失时按就近位置降级。 const subtitle = controlRight.querySelector('.bpx-player-ctrl-subtitle'); const volume = controlRight.querySelector('.bpx-player-ctrl-volume'); if (subtitle) { subtitle.insertAdjacentElement('afterend', toggleBtn); } else if (volume) { volume.insertAdjacentElement('beforebegin', toggleBtn); } else { controlRight.prepend(toggleBtn); } } function removeCommentButton() { if (toggleBtn && toggleBtn.parentNode) { toggleBtn.remove(); toggleBtn = null; } } function disconnectControlObserver() { if (controlWaitObserver) { controlWaitObserver.disconnect(); controlWaitObserver = null; } } function onFullscreenChange() { const mode = getScreenMode(); const nowActive = detectFullscreen();
if (nowActive) { // 回到全屏(含 web<->full 互转),取消待执行的退出 if (leaveFullscreenTimer) { clearTimeout(leaveFullscreenTimer); leaveFullscreenTimer = null; } // 互转时 activeScreen 变化,但 isEmbedded 状态保持不变,评论区不会被重建 if (activeScreen !== mode) { activeScreen = mode; isFullscreen = true; } if (!toggleBtn) { createCommentButton(); if (!toggleBtn) observeControlRight(); } return; }
// 进入 normal / wide:延迟退出,容忍模式切换过程中的瞬时中间态 if (isFullscreen && !leaveFullscreenTimer) { leaveFullscreenTimer = setTimeout(() => { leaveFullscreenTimer = null; const current = getScreenMode(); if (CONFIG.fullscreenScreens.indexOf(current) !== -1) return; // 又回到全屏了 isFullscreen = false; activeScreen = null; if (isEmbedded) restoreComments(); removeCommentButton(); disconnectControlObserver(); }, 300); } } function observeControlRight() { if (getControlRight()) { createCommentButton(); return; } if (controlWaitObserver) controlWaitObserver.disconnect(); controlWaitObserver = new MutationObserver(() => { if (getControlRight()) { controlWaitObserver.disconnect(); controlWaitObserver = null; if (isFullscreen) createCommentButton(); } }); controlWaitObserver.observe(document.body, { childList: true, subtree: true }); setTimeout(() => { if (controlWaitObserver) { controlWaitObserver.disconnect(); controlWaitObserver = null; } }, 10000); }
// ========== v2 新增:视频切换检测 + 评论区跟随 ========== // B站是SPA,切换视频(合集分集、推荐视频等)不刷新页面,评论区的 // data-params(目标aid)不会自动更新,需要手动同步并重载。 function getCurrentAid() { try { const s = window.__INITIAL_STATE__; return (s && s.aid) || null; } catch (e) { return null; } } function syncComments(retries = 3, tries = 0) { const bc = getCommentComponent(); const aid = getCurrentAid(); if (!bc || !aid) { if (tries < retries) setTimeout(() => syncComments(retries, tries + 1), 1000); return; } const want = '1,' + aid; if (bc.getAttribute('data-params') === want) return; // 已是当前视频,无需处理 bc.setAttribute('data-params', want); // 复用嵌入时的强制重载逻辑,让评论区拉取新视频的评论 const app = getCommentApp(); if (app) reloadComments(app); // 若B站状态尚未更新完成,稍后重试 if (tries < retries) setTimeout(() => syncComments(retries, tries + 1), 1500); } function getBvFromUrl() { const m = location.pathname.match(/\/video\/(BV\w+)/); return m ? m[1] : null; } function setupNavigationWatch() { // B站切换视频走 history.pushState/replaceState(SPA导航,不触发popstate),打补丁捕获 const wrap = function (orig) { return function () { const r = orig.apply(this, arguments); setTimeout(() => syncComments(), 800); return r; }; }; history.pushState = wrap(history.pushState); history.replaceState = wrap(history.replaceState); window.addEventListener('popstate', () => { setTimeout(() => syncComments(), 800); }); }
function startPolling() { if (pollTimer) clearInterval(pollTimer); let lastBv = getBvFromUrl(); pollTimer = setInterval(() => { onFullscreenChange(); // 轮询兜底:仅比对URL中的BV号,防止补丁漏掉的导航方式 const bv = getBvFromUrl(); if (bv && bv !== lastBv) { lastBv = bv; syncComments(); } }, CONFIG.pollInterval); } function watchScreenMode() { const container = getLayoutRoot(); if (!container) return false; if (screenObserver && screenObserverTarget === container) return true; if (screenObserver) { screenObserver.disconnect(); screenObserver = null; } screenObserver = new MutationObserver(onFullscreenChange); screenObserver.observe(container, { attributes: true, attributeFilter: ['data-screen'] }); screenObserverTarget = container; return true; } function init() { installMoveNoiseGuard(); // 浏览器 Fullscreen API 事件(完全全屏会触发) ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'].forEach(evt => document.addEventListener(evt, onFullscreenChange) ); // 网页全屏/完全全屏切换的本质是 .bpx-player-container 的 data-screen 变化, // 直接监听该属性;容器可能尚未渲染,用轮询兜底补挂。 if (!watchScreenMode()) { const waitContainer = setInterval(() => { if (watchScreenMode()) clearInterval(waitContainer); }, 500); setTimeout(() => clearInterval(waitContainer), 30000); } setupNavigationWatch(); startPolling(); setTimeout(onFullscreenChange, 1000); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', init); } else { init(); } })();
|