前言

刷B站时,有些视频就想边放边看看评论区。往下滑到评论区,视频会以画中画的形式显示,但太小了,也看不了弹幕。

于是我想到,模仿油管,在全屏模式下放置一个按钮可以呼出评论区,显示在右侧。

实现的效果如下:
全屏显示评论区

这个功能只在网页全屏和完全全屏下显示,点击按钮启用,再次点击恢复原样;视频与评论区之间可以拖拽,随时调整两者的屏占比。

默认状态和宽屏模式完全不干预,不影响正常体验。

普通视频页和番剧、纪录片这类影视页(/bangumi/play/)都能用。两类页面的评论区结构不一样,脚本各做了一套适配,效果一致。

安装

前提-安装油猴插件

以Windows自带的Edge浏览器为例:
安装油猴

在浏览器右上角点击扩展按钮,选择菜单里的[ 获取Microsoft Edge扩展 ],然后搜索“篡改猴”,点击获取安装。

安装脚本

方法一:从脚本仓库安装

脚本文件我已经上传到了GreasyFork (油叉),可以在上面找到B站网页全屏模式显示评论区(播放器下方按钮点击启用),点击安装即可。

如果网络问题无法打开该网站,那么就可以尝试方法二。

之前装过旧版本的,需要在油猴里更新到 2.4,番剧、影视页的支持是 2.1 加的,完全全屏下的图片查看和「回网页全屏」按钮是 2.2 加的,2.3 把按钮图标换成了B站原生的、并处理了切回网页全屏时的过渡,2.4 加了可以自己绑的快捷键。

方案二:自定义脚本

添加脚本

在右上角找到油猴的图标,点击弹出菜单,再点击添加新脚本。

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();
}
})();

在弹出的脚本编辑页面,全选删除,再把上面这段脚本代码复制进去,按Ctrl+s进行保存即可。

原理介绍

核心功能

  1. 视频画面左移,宽度被压缩。
  2. 评论区嵌入播放器右侧,默认35%的宽度,样式完全沿用B站自带。
  3. 中间有可拖拽的分隔条:拖动即可实时调整视频与评论区的屏占比(默认范围 15%~70%),松手后自动记住,下次打开还是这个比例。分隔条平时完全隐形,鼠标移上去或拖拽时才显出一条贯穿上下的细线,不干扰观看。
  4. 评论区会强制重载,确保内容正常显示。
    再次点击按钮,评论区恢复原位,视频恢复全宽。
  5. 切换视频/分集时评论区自动跟随:只把评论组件指向新视频并重载,不刷新整个网页、不中断播放。
  6. 网页全屏与完全全屏都支持,两者互切时侧栏不会丢失;默认状态和宽屏模式完全不干预。
  7. 番剧、纪录片等影视页同样支持:/bangumi/play/ 的评论区容器和 aid 来源都与普通视频页不同,脚本另做了一套适配。
  8. 按钮带悬停提示:显示「打开侧边评论」或「关闭侧边评论」,文案跟着当前状态变,样式与播放器自带的提示一致。
  9. 完全全屏下评论区的图片正常查看:查看器铺满整个屏幕,与网页全屏下表现一致。
  10. 完全全屏下多一个「回网页全屏」按钮:B站进入完全全屏后会隐藏自己的网页全屏按钮,脚本补一个在同一个格子上,图标沿用B站原生的,点一下直接回到网页全屏,不用先退出再重新点,切换过程也不会跳两下。
  11. 可以自己绑一个快捷键开关侧边评论:默认关闭,在 commentHotkey 里填 'alt+c' 这类写法就生效,只在网页全屏和完全全屏下响应。

可修改内容

默认评论区占比为35%,这个值只是初始值——拖拽分隔条即可随时调整,范围默认 15%~70%,松手后会记住。想改初始值或范围,修改代码中的这几个配置即可:

1
2
3
4
5
6
7
// 初始占比(拖拽调整后会记住新的占比)
commentWidth: '35%',
// 拖拽可调整的占比范围
minCommentRatio: 0.15,
maxCommentRatio: 0.7,
// 是否记住拖拽调整后的占比
rememberWidth: true,

默认同时支持网页全屏(web)和完全全屏(full),如果只想保留其中一种,可修改 fullscreenScreens:

1
2
3
4
// 只支持网页全屏
fullscreenScreens: ['web'],
// 只支持完全全屏
fullscreenScreens: ['full'],

另外,B站评论组件在被搬动或重建时,会向控制台抛出一条没有任何信息的报错(Uncaught (in promise) undefined),这是组件自身的缺陷——不装本脚本,单纯切换分集时同样会出现。脚本默认把自己搬运评论区所引发的那条静默掉(只静默“搬运前后 3 秒内 + 报错信息为空”的定向场景);如果你更希望看到页面的原始报错,可以把 suppressMoveNoise 改为 false。

快捷键默认是关的,commentHotkey 留空就一个按键监听都不注册。想用就填一个组合键:

1
2
3
4
5
6
7
8
// 关闭(默认)
commentHotkey: '',
// Alt + C
commentHotkey: 'alt+c',
// Ctrl + Shift + B
commentHotkey: 'ctrl+shift+b',
// 单键也行
commentHotkey: 'f9',

修饰键支持 ctrl、alt、shift、meta(cmd、win 同义),最后一个是主键,字母、数字、f1~`f12、space` 都能填。

按键是在捕获阶段拦下来的,所以填了播放器自己也在用的键(比如 space、f)会盖掉播放器原来的行为。只在网页全屏和完全全屏下响应,普通、宽屏模式按了没反应;焦点在输入框里(比如正在打评论)时也不抢。

代码逻辑

1. 全屏状态的精准捕获(触发条件)

B站播放器的模式由 .bpx-player-container 的 data-screen 属性标识:normal(默认)→ wide(宽屏)→ web(网页全屏)→ full(完全全屏)。脚本以它作为唯一判据,支持哪些模式由 fullscreenScreens 决定:

  • 监听 data-screen 变化:用 MutationObserver 直接盯住该属性,模式一变立刻响应。
  • 监听标准全屏API:监听 fullscreenchange 等事件——完全全屏会额外触发浏览器的 Fullscreen API。
  • 兜底轮询(Polling):每 500ms 执行一次 onFullscreenChange 检查,防止播放器容器晚于脚本渲染。
    • 进入 web/full 时创建按钮;两者互切时不重建嵌入状态(用 activeScreen 记录当前模式),评论区不会被搬来搬去。
    • 退出到 normal/wide 时用 300ms 延迟定时器确认后再退出,容忍模式切换过程中的瞬时中间态;确认真的退出了,才销毁按钮并恢复评论区位置。

2. 评论区的“搬运”与布局重置(核心交互)

点击按钮触发 toggleEmbed,执行 doEmbed 函数:

  • 保存现场:搬运前保存评论区的 parentNode 和 nextSibling,并把要改动的元素原样式逐项记下来(rememberStyle),恢复时精确还原。
  • 创建容器:动态生成一个 div#embedded-comment-container,只负责“占位 + 滚动”;背景取B站主题变量 var(--bg1, #fff)(浅色为白、深色自动跟随),顶部留 10px 间距,评论区内容一律沿用B站自带样式。
  • Flex布局改造:把布局根(.bpx-player-container)设为 display: flex + flex-direction: row,视频区(.bpx-player-primary-area)与评论容器左右并排(默认 65% / 35%,可拖拽调整)。完全全屏时 .bpx-player-container 本身就是浏览器的全屏元素,所以两种模式共用同一套布局,互切不会失效。
  • 可拖拽分隔条:在视频区和评论容器之间插入一个 6px 宽的分隔条(热区),用 pointerdown + setPointerCapture 接管拖拽,实时把新占比写回两侧的 flex-basis。分隔条本体取评论面板同色(var(--bg1, #fff))打底,既挡住视频元素从下方透出,又让分隔区域在默认状态下与评论区融为一体;内部只有一条 2px 的竖线握把,默认 opacity: 0 不显示,鼠标悬停或拖拽时才淡入,并贯穿容器顶部到底部。握把用 justify-content: flex-start 贴在分隔条左边缘(也就是紧贴视频画面),所以从左到右是「黑视频 → 灰握把 → 白评论」的自然过渡;若让它居中,握把左侧会夹出一条 2px 白缝,在黑色视频背景上很显眼。宽度写成 calc((100% - 6px) * 占比),所以两侧加上分隔条永远正好等于容器宽度,窗口缩放也会自动跟随;占比限制在 15%~70%,松手后写入 localStorage,下次进入沿用。
  • 截断滚轮冒泡:播放器把“滚轮调音量”的监听挂在 document 和播放器根节点上(都在冒泡阶段),而侧栏就在播放器容器内部,滚轮冒泡上去会误触音量。于是在容器上就地 stopPropagation(),wheel/mousewheel/DOMMouseScroll 三种事件名都拦。只截断冒泡、不 preventDefault,所以侧栏自身的滚动照常,播放器区域的滚轮调音量也不受影响。
  • 强制重载评论:找到评论组件(bili-comments),移除并重新添加 lazy-load 属性,并调用其内部的 reload() 方法,避免评论因DOM迁移而加载失败。

3. 评论按钮的注入(UI入口)

脚本会定位播放器控制栏的右侧区域(.bpx-player-control-bottom-right),在 【字幕】和【音量】两个按钮之间 插入一个自定义的 div 按钮,内嵌一个对话气泡样式的SVG图标。点击该按钮即执行切换逻辑。

番剧、影视页的控制栏没有字幕按钮,找不到就退到【音量】按钮前面插;两个都找不到时插到最前面。

悬停提示是照着播放器原生那套自己做的。B站的按钮提示由播放器 JS 统一管:按钮上挂 data-name,播放器去 .bpx-player-tooltip-area 里找同名节点,算好坐标再显示。我们的按钮不在它的名单里,所以另建一个外观相同的节点:黑底白字、12px、圆角 2px,水平中心与按钮对齐,底部距按钮顶部 28px(这个间距是量着原生提示抄的)。节点挂在 .bpx-player-tooltip-area 里,不挂 body。完全全屏时浏览器只渲染全屏元素内部的内容,挂到外面会看不见。文案跟着状态走,鼠标停在按钮上点一下,提示会立刻从「打开侧边评论」变成「关闭侧边评论」。

4. 切换视频时评论区如何跟随(SPA特性)

B站视频页面是单页应用(SPA),切换视频(合集分集、右侧推荐等)走的是 history.pushState/replaceState,不会触发 popstate,也不会刷新页面。结果是播放器换成了新视频,而评论组件的 data-params(值为 "1,<aid>",决定加载哪个视频的评论)还停留在旧视频上。

老版本的做法是“发现URL变了就 location.reload()”,简单但粗暴:整页重建、播放中断。新版本直接去拧那个开关:

  • 捕获导航:给 history.pushState/replaceState 打补丁,并监听 popstate;再用 500ms 轮询比对URL里的 BV 号 / ep 号兜底,防止漏掉某种导航方式。
  • 取当前视频的 aid:普通视频页从 window.__INITIAL_STATE__.aid 读;番剧、影视页没有这个对象,改读 window.player.getManifest().aid。
  • 同步并重载:把评论组件的 data-params 写成 "1," + aid,再调用 reload()。评论区原地换成新视频的评论,页面不刷新、播放不中断。

5. 番剧、纪录片页面的四处差异

/bangumi/play/ 下是另一套页面(Next.js 渲染),结构跟普通视频页对不上,脚本做了这些适配:

  • 评论区容器:这类页面没有 #commentapp,评论模块是 div#comment-module,里面再套一层 #comment-body 放 bili-comments。配置项因此从单个选择器改成列表 commentSelectors,按顺序取第一个存在的节点。
  • aid 的来源:页面没有 window.__INITIAL_STATE__。首屏注入的 window.__playinfo__.result.arc.aid 只在打开页面时有效,切集后不更新(实测切完 15 秒还是旧值),所以改从 window.player.getManifest() 取,切集后它返回新一集的 aid、cid、episodeId。
  • 切集后评论不跟随:普通视频页由B站自己更新评论的 data-params,影视页没有,切完还是上一集的评论。同步逻辑对两类页面一视同仁,这个问题顺带一起修了。
  • 控制栏会重建:切集时控制栏整块换掉,按钮跟着消失。轮询里用 isConnected 检查按钮是否还在文档中,掉了就补一个。评论模块本身被换掉的情况没在这几个页面上碰到,但换季、换番时页面会整块重渲染,所以也留了一个检测:一旦搬进侧栏的节点脱离文档,就清掉侧栏、按新节点重建。

6. 评论区的图片查看器挂在哪儿

评论区点开图片,B站用的是独立的 PhotoSwipe 实例:一个 .pswp 元素,position: fixed 铺满视口,z-index: 100000。首次打开时由 document.body.appendChild 挂到 body 上,关掉后节点销毁,下次再建。

全屏元素的绘制范围是一条硬约束:浏览器只绘制全屏元素内部的内容,挂在 body 上的节点不在其中,改 z-index 也没有用。所以完全全屏期间,查看器必须落在全屏元素里面。

脚本的做法是给 document.body.appendChild 打一个补丁:当新增节点是 .pswp、且当前正处于播放器全屏,就直接返回 fsEl.appendChild(node),让节点从一开始就生在容器里。不先挂到 body 再搬过去,是因为节点被移出文档再插回去时,PhotoSwipe 正在跑的打开动画会中断重来,看起来就是卡一下。补丁对整页生效,所以判断只留一层 .pswp 的类名检查,其余节点原样放行。

换父不影响定位:.bpx-player-container 没有 transform、filter、contain,不会成为 position: fixed 的包含块,查看器铺满的仍然是整个视口。

补丁只覆盖「首次创建」这一条路径。查看器已经开着的时候进入或退出全屏、web/full 互切,走的是 syncViewerHost():全屏期间不在全屏元素里就搬进去,退出全屏后还留在容器里就搬回 body。500ms 的轮询里也带着这个检查。

7. 完全全屏下补一个「回网页全屏」按钮

B站进入完全全屏后会把自己的网页全屏按钮(.bpx-player-ctrl-web)和宽屏按钮一起设成 display: none,只留一个【全屏】。想回网页全屏,只能先退出、再点一次网页全屏。

脚本在 mode === 'full' 时插一个自己的按钮,插在 .bpx-player-ctrl-full 前面,正好落在被隐藏的那个按钮占的格子上(实测两者的 x 坐标、宽度、图标高度完全一致)。图标直接借B站「进入网页全屏」那个节点(.bpx-player-ctrl-web-enter)的 innerHTML:它一直待在 DOM 里,只是被 display: none 藏起来。原生图标是 lottie 导出的,一条路径将近 4KB,抄进脚本没意义,借节点省事又不会走样。

按钮的盒子结构也得照着原生来。.bpx-player-ctrl-btn-icon 只给了 width: 100%,高度靠里面的 .bpx-common-svg-icon 撑(网页全屏、完全全屏下是 28px)。盒子要用 div,用 span 会变成行内元素、高度塌成 0,图标跟着往下坠几像素。

点击后没有直接调播放器接口——没找到可用的。实际做法是:先 document.exitFullscreen(),等 data-screen 离开 full,再确认落点。退出全屏后B站会自己把模式落回 web 或 normal,落到哪个并不确定,所以要多一步判断:已经是 web 就不动,还是 normal 才去点它自己的网页全屏按钮。这一步省不得,网页全屏按钮是开关,多按一下反而退出了。

麻烦的是这段时间里的画面。从网页全屏进完全全屏,画面只是从窗口撑到屏幕,一步到位;反过来退出时,浏览器先把视口缩回窗口,B站同时把播放器摆回页面里的位置,等网页全屏真正生效再撑满一次——中间那几帧是 normal 布局,看着就是跳两下。

所以退出前先把播放器容器(.bpx-player-container)临时钉成 position: fixed、铺满视口,并记下它原来的内联样式;等网页全屏生效、B站自己的定位规则接手之后,再把内联样式还原。整个过程里容器的尺寸一直是视口大小,画面只经历「屏幕 → 窗口」这一次变化,和退出浏览器全屏本身没有区别。按 8ms 采样整段切换,容器尺寸始终是 1600×900,一次都没有落回 normal 的 1130×682。

模式回到 web 后这个按钮自动移除,B站自己的网页全屏按钮重新露出来。

8. 快捷键怎么匹配

配置是一串字符,按 + 拆开:认得的修饰键(ctrl、alt、shift、meta)置位,剩下的第一个当主键。解析不出主键就整条作废,并在控制台报一句,免得填错了还以为脚本坏了。

匹配时先比四个修饰键的布尔值,再比主键。主键同时看 event.key 和 event.code:key 跟着输入法和键盘布局走(按住 Shift 时是大写字母),code 是物理键位,两个有一个对上就算命中。空格得单独处理,它的 key 就是一个空格字符。

监听挂在 document 的捕获阶段,命中后 preventDefault 加 stopPropagation,播放器自己的按键处理就收不到这次事件了。判断「是不是在打字」用 composedPath()[0] 取真实目标——B站的评论框在 bili-comments 的 shadowRoot 里,event.target 只会给到宿主节点,拦不住。

附注:B站的评论区目前有两套实现——现代组件 bili-comments(带 shadowRoot)和一套旧版 DOM。本脚本针对的是前者,也就是你现在在B站上实际看到的那一套。