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 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
| // ==UserScript== // @name B站网页全屏模式显示评论区(播放器下方按钮点击启用) // @namespace https://magiku.github.io/ // @version 2.2 // @description 网页全屏/完全全屏时在控制栏添加评论按钮,点击后视频左移、评论区嵌入播放器右侧;普通视频页与番剧/影视页通用,切换视频/分集评论自动跟随,无需整页刷新;完全全屏下评论图片可正常查看,并补一个回网页全屏的按钮;可自行绑定快捷键开关侧边评论 // @match https://www.bilibili.com/video/* // @match https://www.bilibili.com/bangumi/play/* // @match https://www.bilibili.com/list/* // @author magiku // @grant none // @license MIT // @icon https://www.bilibili.com/favicon.ico // @downloadURL https://update.greasyfork.org/scripts/593725/B%E7%AB%99%E7%BD%91%E9%A1%B5%E5%85%A8%E5%B1%8F%E6%A8%A1%E5%BC%8F%E6%98%BE%E7%A4%BA%E8%AF%84%E8%AE%BA%E5%8C%BA%EF%BC%88%E6%92%AD%E6%94%BE%E5%99%A8%E4%B8%8B%E6%96%B9%E6%8C%89%E9%92%AE%E7%82%B9%E5%87%BB%E5%90%AF%E7%94%A8%EF%BC%89.user.js // @updateURL https://update.greasyfork.org/scripts/593725/B%E7%AB%99%E7%BD%91%E9%A1%B5%E5%85%A8%E5%B1%8F%E6%A8%A1%E5%BC%8F%E6%98%BE%E7%A4%BA%E8%AF%84%E8%AE%BA%E5%8C%BA%EF%BC%88%E6%92%AD%E6%94%BE%E5%99%A8%E4%B8%8B%E6%96%B9%E6%8C%89%E9%92%AE%E7%82%B9%E5%87%BB%E5%90%AF%E7%94%A8%EF%BC%89.meta.js // ==/UserScript==
(function() { 'use strict'; const CONFIG = { playerSelector: '#bilibili-player', videoWrapSelector: '.bpx-player-video-wrap', //评论区根节点:普通视频页是 #commentapp,番剧/影视(OGV)页是 #comment-module commentSelectors: ['#commentapp', '#comment-module'], controlRightSelector: '.bpx-player-control-bottom-right', //开关侧边评论的快捷键,默认为"c"。 //填法:修饰键用 + 连接,最后一个是主键,例如 'alt+c'、'ctrl+shift+b'、'f9'。 //修饰键支持 ctrl / alt / shift / meta(cmd、win 同义);主键可以是字母、数字、f1~f12、space 等。 //只在网页全屏和完全全屏下响应,焦点在输入框里时不抢按键。 commentHotkey: 'c', //评论区占比大小(默认值;拖拽调整后会记住新的占比) 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 webBtn = null; let returningToWeb = false; let pinSnapshot = null; let tipEl = null; let tipOwner = null; let tipVisible = false; 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 bodyAppendPatched = false; 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() { for (const selector of CONFIG.commentSelectors) { const el = document.querySelector(selector); if (el) return el; } return null; } 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']); // 番剧/影视页的评论模块是页面框架里的一个普通 div,宽度由父级决定; // 搬进侧栏后父级没了参照,显式给 100% 让它铺满侧栏。 rememberStyle(commentApp, ['width', 'minWidth', 'height']);
root.style.display = 'flex'; root.style.flexDirection = 'row'; root.style.alignItems = 'stretch'; primaryArea.style.minWidth = '0'; videoWrap.style.width = '100%'; commentApp.style.width = '100%'; commentApp.style.minWidth = '0';
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); } // 文案跟着状态走;鼠标还停在按钮上时立刻换掉,不用移开再移回来 refreshTip(); } catch (e) {} } // ========== 按钮的悬停提示 ========== // B站播放器的按钮提示是它自己那套:控制栏按钮带 data-name,播放器去 // .bpx-player-tooltip-area 里找同名节点,算好坐标再显示出来。 // 我们的按钮不在它的名单里,所以自己做一个同款:黑底白字、12px、 // 圆角 2px,居中显示在按钮上方,间距与原生提示一致。 function createTooltip() { if (tipEl) return; tipEl = document.createElement('div'); tipEl.className = 'bili-side-comment-tip'; tipEl.setAttribute('role', 'tooltip'); tipEl.style.cssText = ` position: fixed; left: 0; top: 0; z-index: 12000; padding: 6px 8px; border-radius: 2px; background: #000; color: #fff; font-size: 12px; line-height: 18px; white-space: nowrap; pointer-events: none; opacity: 0; visibility: hidden; transition: opacity .15s; `; } function getTooltipHost() { // 完全全屏时浏览器只渲染全屏元素内部的东西,提示必须挂在播放器容器里, // 挂到 body 上会看不见。 return document.querySelector('.bpx-player-tooltip-area') || getLayoutRoot() || document.body; } function commentTipText() { return isEmbedded ? '关闭侧边评论' : '打开侧边评论'; } function updateTipText() { const text = commentTipText(); if (toggleBtn) toggleBtn.setAttribute('aria-label', text); refreshTip(); } // 提示正在显示时,按当前状态把文案重算一遍 function refreshTip() { if (!tipVisible || !tipOwner) return; const fn = tipOwner.__tipText; if (typeof fn === 'function') showTip(tipOwner, fn()); } function showTip(target, text) { if (!target || !tipEl) return; const host = getTooltipHost(); if (tipEl.parentNode !== host) host.appendChild(tipEl); tipEl.textContent = text; // 先归零量尺寸再摆位:文案长度会变,宽度每次都得重新量 tipEl.style.left = '0px'; tipEl.style.top = '0px'; tipEl.style.visibility = 'visible'; const btnRect = target.getBoundingClientRect(); const width = tipEl.offsetWidth; const height = tipEl.offsetHeight; // 原生提示的水平中心与按钮对齐,底部距按钮顶部 28px,照抄这个间距 let left = btnRect.left + btnRect.width / 2 - width / 2; let top = btnRect.top - height - 28; left = Math.max(4, Math.min(window.innerWidth - width - 4, left)); if (top < 4) top = btnRect.bottom + 8; // 上方放不下时翻到按钮下方 tipEl.style.left = Math.round(left) + 'px'; tipEl.style.top = Math.round(top) + 'px'; tipEl.style.opacity = '1'; tipVisible = true; tipOwner = target; } function hideTip() { tipVisible = false; tipOwner = null; if (!tipEl) return; tipEl.style.opacity = '0'; tipEl.style.visibility = 'hidden'; } // 给控制栏按钮挂上「悬停/聚焦显示提示」的一套监听 function bindTip(btn, text) { createTooltip(); btn.__tipText = text; btn.addEventListener('mouseenter', () => showTip(btn, text())); btn.addEventListener('mouseleave', hideTip); btn.addEventListener('focus', () => showTip(btn, text())); btn.addEventListener('blur', hideTip); } 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(); }); bindTip(toggleBtn, commentTipText); // 插到【字幕】与【音量】之间;字幕/音量任一缺失时按就近位置降级。 // 番剧/影视页的控制栏没有字幕按钮,会落到【音量】前面。 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); } updateTipText(); } function removeCommentButton() { hideTip(); if (tipEl) { tipEl.remove(); tipEl = null; } if (toggleBtn && toggleBtn.parentNode) { toggleBtn.remove(); toggleBtn = null; } } // ========== 快捷键开关侧边评论 ========== // 默认不启用:commentHotkey 留空就一个监听都不注册。 // 填了之后按 'alt+c' 这种写法解析,只在网页全屏/完全全屏下响应。 function parseHotkey(text) { if (!text || typeof text !== 'string') return null; const parts = text.toLowerCase().split('+').map((s) => s.trim()).filter(Boolean); const combo = { ctrl: false, alt: false, shift: false, meta: false, key: '' }; for (const part of parts) { if (part === 'ctrl' || part === 'control') combo.ctrl = true; else if (part === 'alt' || part === 'option') combo.alt = true; else if (part === 'shift') combo.shift = true; else if (part === 'meta' || part === 'cmd' || part === 'win' || part === 'super') combo.meta = true; else if (!combo.key) combo.key = part; } return combo.key ? combo : null; } function isTypingTarget(target) { if (!target || target.nodeType !== 1) return false; const tag = target.tagName; if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true; return target.isContentEditable === true; } function hotkeyMatches(e, combo) { if (e.ctrlKey !== combo.ctrl || e.altKey !== combo.alt) return false; if (e.shiftKey !== combo.shift || e.metaKey !== combo.meta) return false; const key = String(e.key || '').toLowerCase(); const code = String(e.code || '').toLowerCase(); // key 会跟着输入法和布局变,code 是物理键位,两个都对一下 if (key === combo.key || code === combo.key) return true; // 空格特殊:key 是 ' ',code 是 'Space' return combo.key === 'space' && (key === ' ' || code === 'space'); } function setupHotkey() { const combo = parseHotkey(CONFIG.commentHotkey); if (!combo) { if (CONFIG.commentHotkey) console.warn('[B站侧边评论] commentHotkey 写法不认识:', CONFIG.commentHotkey); return; } // 用捕获阶段:配置了快捷键就让它优先,不被播放器自己的按键(空格、f、d 之类)吃掉 document.addEventListener('keydown', (e) => { if (e.repeat || e.isComposing) return; if (!hotkeyMatches(e, combo)) return; // 评论框里打字时不抢按键(B站评论组件在 shadow DOM 里,取 composedPath 的第一个) const target = (e.composedPath && e.composedPath()[0]) || e.target; if (isTypingTarget(target)) return; // 侧栏只在网页全屏/完全全屏下有意义 if (!detectFullscreen()) return; e.preventDefault(); e.stopPropagation(); toggleEmbed(); }, true); } // ========== 完全全屏 → 网页全屏 ========== // 完全全屏时B站把网页全屏按钮设成 display:none,切过去只能先退出全屏、 // 再点一次网页全屏。这里补一个按钮代劳。 // 但「退出浏览器全屏」和「网页全屏生效」之间有一段时间播放器处于 normal 布局: // 画面会先缩回页面里那一块,再撑满窗口,看着就是跳两下。所以退出前先把 // 播放器容器临时钉成铺满视口,等网页全屏真正生效再撤销——中间那几帧的 // 尺寸和网页全屏一模一样,画面只经历「屏幕 → 窗口」这一次变化。 const PIN_PROPS = ['position', 'top', 'left', 'width', 'height', 'zIndex', 'margin']; function pinToViewport() { if (pinSnapshot) return; const el = getLayoutRoot(); if (!el) return; const values = {}; PIN_PROPS.forEach((p) => { values[p] = el.style[p]; }); pinSnapshot = { el, values }; el.style.position = 'fixed'; el.style.top = '0'; el.style.left = '0'; el.style.width = '100%'; el.style.height = '100%'; el.style.zIndex = '100000'; el.style.margin = '0'; } function unpinFromViewport() { if (!pinSnapshot) return; const { el, values } = pinSnapshot; pinSnapshot = null; PIN_PROPS.forEach((p) => { el.style[p] = values[p]; }); } function returnToWebScreen() { if (returningToWeb) return; returningToWeb = true; pinToViewport(); const started = Date.now(); let clicked = false; const finish = () => { returningToWeb = false; // 网页全屏已经生效,再等一小会儿让B站自己的定位规则接手,然后撤掉临时样式 setTimeout(unpinFromViewport, 400); }; const step = () => { const mode = getScreenMode(); if (mode === 'web') { finish(); return; } if (mode === 'full') { if (Date.now() - started < 1500) { setTimeout(step, 30); return; } finish(); return; } // 已经离开 full 但还不是 web:补点一次网页全屏。只点一次—— // 这个按钮是开关,多点几下会来回横跳。 if (!clicked) { clicked = true; const btn = document.querySelector('.bpx-player-ctrl-web'); if (btn) btn.click(); setTimeout(step, 30); return; } if (Date.now() - started < 2000) { setTimeout(step, 30); return; } finish(); }; if (document.fullscreenElement) { try { const p = document.exitFullscreen(); if (p && typeof p.catch === 'function') p.catch(() => {}); } catch (e) {} } setTimeout(step, 30); } // 图标直接借B站「进入网页全屏」那个节点(.bpx-player-ctrl-web-enter)。 // 原生图标是 lottie 导出的,一条路径四位数精度、将近 4KB,抄进脚本没意义; // 这个节点一直待在 DOM 里(完全全屏时只是被 display:none 藏起来),拿来用就是。 // 万一哪天取不到,退回下面这份手绘的等价图形(圆角方片挖四个 L 形缺口)。 const WEB_ICON_FALLBACK = '<span class="bpx-common-svg-icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 88 88" preserveAspectRatio="xMidYMid meet" style="width:100%;height:100%"><path fill="#fff" fill-rule="evenodd" d="M16 8h56a8 8 0 0 1 8 8v56a8 8 0 0 1-8 8H16a8 8 0 0 1-8-8V16a8 8 0 0 1 8-8zM16 24h16v8h-8v8h-8zM72 24H56v8h8v8h8zM16 64h16v-8h-8v-8h-8zM72 64H56v-8h8v-8h8z"/></svg></span>'; function webReturnIconHtml() { const native = document.querySelector('.bpx-player-ctrl-web .bpx-player-ctrl-web-enter'); return native && native.innerHTML ? native.innerHTML : WEB_ICON_FALLBACK; } function createWebScreenButton() { // 番剧/影视页切集时控制栏会整体重建,按钮被一并清掉 if (webBtn && !webBtn.isConnected) webBtn = null; if (webBtn) return; const controlRight = getControlRight(); if (!controlRight) return; webBtn = document.createElement('div'); webBtn.className = 'bpx-player-ctrl-btn bpx-player-ctrl-web-return'; webBtn.setAttribute('role', 'button'); webBtn.setAttribute('aria-label', '切换到网页全屏'); webBtn.tabIndex = 0; // 图标盒子用 div:B站的 .bpx-player-ctrl-btn-icon 只给了 width:100%, // 高度靠里面的 .bpx-common-svg-icon 撑(网页全屏/完全全屏下是 28px)。 // 用 span 会变成行内元素,盒子高度塌成 0,图标跟着往下坠几像素。 const iconBox = document.createElement('div'); iconBox.className = 'bpx-player-ctrl-btn-icon'; iconBox.innerHTML = webReturnIconHtml(); webBtn.appendChild(iconBox); webBtn.addEventListener('click', (e) => { e.stopPropagation(); returnToWebScreen(); }); bindTip(webBtn, () => '切换到网页全屏'); // 完全全屏下B站的网页全屏按钮占着这个位置(只是被隐藏了),插在【全屏】前面 const full = controlRight.querySelector('.bpx-player-ctrl-full'); if (full) full.insertAdjacentElement('beforebegin', webBtn); else controlRight.appendChild(webBtn); } function removeWebScreenButton() { if (webBtn && webBtn.parentNode) { webBtn.remove(); webBtn = null; } } function disconnectControlObserver() { if (controlWaitObserver) { controlWaitObserver.disconnect(); controlWaitObserver = null; } } // ========== 完全全屏下,评论区图片查看器的挂载点 ========== // 评论区点开图片后,B站用一个独立的 PhotoSwipe 实例(.pswp,z-index 100000) // 覆盖整个视口,首次打开时挂到 document.body 上,之后复用同一个节点。 // 完全全屏时浏览器只绘制全屏元素内部的内容,body 上的节点不在绘制范围内, // 所以全屏期间要把查看器放进播放器容器,退出全屏再搬回 body。 function getViewerEl() { return document.querySelector('.pswp'); } function syncViewerHost() { const viewer = getViewerEl(); if (!viewer) return; const root = getLayoutRoot(); const fsEl = document.fullscreenElement; // 全屏元素是播放器容器(或它内部的东西)时,查看器只有待在它里面才会被画出来 const playerFullscreen = !!(fsEl && root && (fsEl === root || root.contains(fsEl))); if (playerFullscreen) { if (!fsEl.contains(viewer)) fsEl.appendChild(viewer); return; } // 退出全屏后搬回 body,免得它跟着播放器容器一起被布局和裁切 if (root && viewer.parentElement === root) document.body.appendChild(viewer); } function watchViewerMount() { // 查看器是首次点开图片时才建的,B站固定往 document.body 上挂。 // 这里直接把这一次 appendChild 接到全屏元素里:先挂 body 再搬家, // 等于在打开动画刚开始时把节点拆了重插,动画会重来一遍(看起来就是卡一下)。 if (!document.body || bodyAppendPatched) return; bodyAppendPatched = true; const original = document.body.appendChild; document.body.appendChild = function(node) { if (node && node.nodeType === 1 && node.classList && node.classList.contains('pswp')) { const fsEl = document.fullscreenElement; const root = getLayoutRoot(); if (fsEl && root && (fsEl === root || root.contains(fsEl))) return fsEl.appendChild(node); } return original.call(this, node); }; } 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; } // 番剧/影视页切集时控制栏会整体重建,按钮被一并清掉, // 这里用 isConnected 判断按钮是否还在文档里,掉了就补一个。 if (toggleBtn && !toggleBtn.isConnected) toggleBtn = null; if (!toggleBtn) { createCommentButton(); if (!toggleBtn) observeControlRight(); } // B站在完全全屏下把网页全屏按钮设成 display:none,补一个替代的; // 回到网页全屏时它自己的按钮就露出来了,把补的那个撤掉。 if (mode === 'full') createWebScreenButton(); else removeWebScreenButton(); // 进入全屏(或 web/full 互切)时,把可能已经打开的图片查看器搬进来 syncViewerHost(); 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(); removeWebScreenButton(); disconnectControlObserver(); // 退出全屏后查看器得搬回 body,否则它会跟着播放器容器一起被布局 syncViewerHost(); }, 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() { // 普通视频页:页面初始状态里就有当前 aid try { const s = window.__INITIAL_STATE__; if (s && s.aid) return s.aid; } catch (e) {} // 番剧/影视页没有 __INITIAL_STATE__,aid 要从播放器 manifest 里取。 // 注意不能用 __playinfo__:它是首屏注入的,切集后不会更新。 try { const p = window.player; const manifest = p && typeof p.getManifest === 'function' ? p.getManifest() : null; if (manifest && manifest.aid) return manifest.aid; } 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 getMediaKeyFromUrl() { // 视频页用 BV 号,番剧/影视页用 ep(单集)或 ss(整季)号 const m = location.pathname.match(/\/(?:video\/(BV\w+)|bangumi\/play\/((?:ep|ss)\d+))/); return m ? (m[1] || m[2]) : 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 ensureEmbedAlive() { if (!isEmbedded) return; if (embeddedCommentApp && embeddedCommentApp.isConnected) return; forceCleanupEmbed(); if (isFullscreen) embedComments(true); }
function startPolling() { if (pollTimer) clearInterval(pollTimer); let lastKey = getMediaKeyFromUrl(); pollTimer = setInterval(() => { onFullscreenChange(); ensureEmbedAlive(); syncViewerHost(); // 轮询兜底:仅比对URL里的视频/剧集标识,防止补丁漏掉的导航方式 const key = getMediaKeyFromUrl(); if (key && key !== lastKey) { lastKey = key; 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(); // 图片查看器是首次点开图片时才创建的,盯住 body 的新增节点把它接住 watchViewerMount(); // 浏览器 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(); setupHotkey(); startPolling(); setTimeout(onFullscreenChange, 1000); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', init); } else { init(); } })();
|