前言

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

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

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

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

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

安装

前提-安装油猴插件

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

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

安装脚本

方法一:从脚本仓库安装

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

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

方案二:自定义脚本

添加脚本

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

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

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

原理介绍

核心功能

  1. 视频画面左移,宽度被压缩。
  2. 评论区嵌入播放器右侧,默认35%的宽度,样式完全沿用B站自带。
  3. 中间有可拖拽的分隔条:拖动即可实时调整视频与评论区的屏占比(默认范围 15%~70%),松手后自动记住,下次打开还是这个比例。分隔条平时完全隐形,鼠标移上去或拖拽时才显出一条贯穿上下的细线,不干扰观看。
  4. 评论区会强制重载,确保内容正常显示。
    再次点击按钮,评论区恢复原位,视频恢复全宽。
  5. 切换视频/分集时评论区自动跟随:只把评论组件指向新视频并重载,不刷新整个网页、不中断播放。
  6. 网页全屏与完全全屏都支持,两者互切时侧栏不会丢失;默认状态和宽屏模式完全不干预。

可修改内容

默认评论区占比为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。

代码逻辑

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图标。点击该按钮即执行切换逻辑。

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

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

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

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

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