-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
503 lines (420 loc) · 16.8 KB
/
content.js
File metadata and controls
503 lines (420 loc) · 16.8 KB
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
/**
* Subtitle Blocker - Content Script
* 负责检测视频、注入遮挡层、处理交互逻辑
*/
class SubtitleBlocker {
constructor() {
this.activeVideo = null;
this.blockerHost = null;
this.blurLayer = null;
this.resizeObserver = null;
this.antiRemovalObserver = null; // 防删除监听器
this.isDragging = false;
this.isResizing = false;
this.startY = 0;
this.startHeight = 0;
this.startBottom = 0; // 用于记录拖拽时的底部距离
// 配置项 (后续可从 Storage 读取)
this.config = {
enabled: true,
blurAmount: 15,
defaultHeightPercent: 15, // 默认高度占视频高度的百分比
bottomOffsetPercent: 5, // 默认底部距离占视频高度的百分比
};
// Shadow DOM 样式
this.styles = `
:host {
position: absolute;
z-index: 2147483647;
pointer-events: none;
display: flex;
flex-direction: column;
justify-content: flex-end;
align-items: center;
overflow: hidden;
top: 0; left: 0; width: 100%; height: 100%;
}
.sb-blur-layer {
width: 100%;
height: 15%;
background-color: rgba(0, 0, 0, 0.1);
backdrop-filter: blur(15px);
-webkit-backdrop-filter: blur(15px);
pointer-events: none; /* 允许点击穿透 */
position: relative;
transition: opacity 0.3s ease, backdrop-filter 0.3s ease;
border-top: 1px solid rgba(255, 255, 255, 0.1);
box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.2);
/* 边缘渐进羽化效果 (丝滑版) */
-webkit-mask-image:
linear-gradient(to right, transparent 0%, black 10%, black 90%, transparent 100%),
linear-gradient(to bottom, transparent 0%, black 20%, black 80%, transparent 100%);
-webkit-mask-composite: source-in;
mask-image:
linear-gradient(to right, transparent 0%, black 10%, black 90%, transparent 100%),
linear-gradient(to bottom, transparent 0%, black 20%, black 80%, transparent 100%);
mask-composite: intersect;
}
.sb-blur-layer.sb-hover-active {
opacity: 0.1;
backdrop-filter: blur(2px);
-webkit-backdrop-filter: blur(2px);
}
/* 交互状态(拖拽/调整大小)时强制显示,优先级高于 hover-active */
.sb-blur-layer.sb-interacting {
opacity: 1 !important;
backdrop-filter: blur(15px) !important; /* 恢复高斯模糊 */
-webkit-backdrop-filter: blur(15px) !important;
}
/* 保留直接悬停在遮挡条上的效果 (如果需要更清晰) */
.sb-blur-layer:hover {
opacity: 0.2;
}
.sb-resize-handle {
width: 100%;
height: 10px;
position: absolute;
top: -5px;
left: 0;
cursor: ns-resize;
z-index: 10;
pointer-events: auto; /* 手柄需要响应点击 */
}
/* Shift 模式下,允许拖拽整个遮挡条 */
.sb-blur-layer.sb-shift-mode {
pointer-events: auto;
cursor: grab;
background-color: rgba(255, 255, 255, 0.15); /* 提示用户可拖拽 */
}
.sb-blur-layer.sb-shift-mode:active {
cursor: grabbing;
}
:host(.sb-hidden) {
display: none !important;
}
`;
this.init();
}
init() {
// 监听视频播放事件 (捕获阶段,确保能抓到)
document.addEventListener('play', this.handlePlay.bind(this), true);
// 监听全屏变化
document.addEventListener('fullscreenchange', this.handleFullscreenChange.bind(this));
// 监听窗口大小变化
window.addEventListener('resize', () => {
if (this.activeVideo) this.updateBlockerPosition();
});
// 检测页面上已有的视频 (防止插件加载晚于视频播放)
this.detectExistingVideos();
// 监听来自 Popup 的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type === 'UPDATE_CONFIG') {
this.updateConfig(request.payload);
}
});
// 加载初始配置
chrome.storage.sync.get(['enabled', 'blurAmount', 'defaultHeightPercent', 'bottomOffsetPercent'], (result) => {
if (result.enabled !== undefined) this.config.enabled = result.enabled;
if (result.blurAmount !== undefined) this.config.blurAmount = result.blurAmount;
if (result.defaultHeightPercent !== undefined) this.config.defaultHeightPercent = result.defaultHeightPercent;
if (result.bottomOffsetPercent !== undefined) this.config.bottomOffsetPercent = result.bottomOffsetPercent;
this.applyConfig();
});
console.log('[Subtitle Blocker] Initialized');
}
detectExistingVideos() {
const videos = document.querySelectorAll('video');
for (const video of videos) {
// 如果视频正在播放,或者它是页面上唯一的视频,就尝试附加
if (!video.paused && !video.ended && video.readyState > 2) {
this.attachToVideo(video);
break; // 只附加到一个
}
}
}
updateConfig(newConfig) {
Object.assign(this.config, newConfig);
this.applyConfig();
}
applyConfig() {
if (!this.blockerHost) return;
// 处理启用/禁用
if (this.config.enabled) {
this.blockerHost.classList.remove('sb-hidden');
} else {
this.blockerHost.classList.add('sb-hidden');
}
// 处理模糊度
if (this.blurLayer) {
const blurVal = `blur(${this.config.blurAmount}px)`;
this.blurLayer.style.backdropFilter = blurVal;
this.blurLayer.style.webkitBackdropFilter = blurVal;
}
}
handlePlay(event) {
const target = event.target;
if (target.tagName === 'VIDEO') {
// 如果切换了视频,重新绑定
if (this.activeVideo !== target) {
this.attachToVideo(target);
}
}
}
findPlayerContainer(video) {
// 优先查找已知的播放器容器 ID 或 Class
// YouTube: #movie_player, .html5-video-player
// Bilibili: #bilibili-player, .bilibili-player-video-wrap
// 通用: 向上查找直到找到一个看起来像播放器的容器
let current = video.parentNode;
while (current && current !== document.body) {
if (current.id === 'movie_player' ||
current.classList.contains('html5-video-player') ||
current.id === 'bilibili-player' ||
current.classList.contains('bilibili-player-video-wrap') ||
current.classList.contains('video-js')) {
return current;
}
current = current.parentNode;
}
// 如果没找到特定容器,回退到直接父级
return video.parentNode;
}
attachToVideo(video) {
console.log('[Subtitle Blocker] Attached to video', video);
this.activeVideo = video;
// 移除旧的遮挡层
this.removeBlocker();
// 创建新的遮挡层
this.createBlocker();
// 启动 ResizeObserver 监听视频大小变化
if (this.resizeObserver) this.resizeObserver.disconnect();
this.resizeObserver = new ResizeObserver(() => {
this.updateBlockerPosition();
});
this.resizeObserver.observe(video);
// 立即更新一次位置
this.updateBlockerPosition();
}
createBlocker() {
// 1. 创建宿主容器 (Host) - 使用不敏感的类名
this.blockerHost = document.createElement('div');
this.blockerHost.className = 'sb-focus-mode-layer';
// 开启 Shadow DOM
const shadow = this.blockerHost.attachShadow({ mode: 'open' });
// 注入样式
const styleSheet = document.createElement('style');
styleSheet.textContent = this.styles;
shadow.appendChild(styleSheet);
// 2. 创建模糊层 (Blur Layer)
this.blurLayer = document.createElement('div');
this.blurLayer.className = 'sb-blur-layer';
// 应用初始配置
const blurVal = `blur(${this.config.blurAmount}px)`;
this.blurLayer.style.backdropFilter = blurVal;
this.blurLayer.style.webkitBackdropFilter = blurVal;
// 设置初始高度
this.blurLayer.style.height = `${this.config.defaultHeightPercent}%`;
// 3. 创建调整大小手柄 (Resize Handle)
const resizeHandle = document.createElement('div');
resizeHandle.className = 'sb-resize-handle';
resizeHandle.title = '拖动调整高度';
resizeHandle.addEventListener('mousedown', this.startResize.bind(this));
// 4. 绑定整体拖拽事件 (配合 Shift 键)
this.blurLayer.addEventListener('mousedown', this.startDrag.bind(this));
// 组装 DOM (添加到 Shadow Root)
this.blurLayer.appendChild(resizeHandle);
// 移除显式的拖拽横条
shadow.appendChild(this.blurLayer);
// 寻找最佳注入容器
const container = this.findPlayerContainer(this.activeVideo);
// 确保容器有定位属性
const containerStyle = window.getComputedStyle(container);
if (containerStyle.position === 'static') {
container.style.position = 'relative';
}
container.appendChild(this.blockerHost);
this.blockerContainer = container; // 保存引用
// 启动防删除监听 (顽强模式)
this.startAntiRemovalObserver(container);
// 监听容器鼠标悬停事件 (自动隐藏)
this.setupHoverListeners(container);
// 监听 Shift 键 (切换拖拽模式)
document.addEventListener('keydown', this.handleKeyDown.bind(this));
document.addEventListener('keyup', this.handleKeyUp.bind(this));
// 全局鼠标事件监听 (用于拖拽和调整大小)
document.addEventListener('mousemove', this.handleMouseMove.bind(this));
document.addEventListener('mouseup', this.handleMouseUp.bind(this));
}
handleKeyDown(e) {
if (e.key === 'Shift' && this.blurLayer) {
this.blurLayer.classList.add('sb-shift-mode');
}
}
handleKeyUp(e) {
if (e.key === 'Shift' && this.blurLayer) {
this.blurLayer.classList.remove('sb-shift-mode');
}
}
setupHoverListeners(container) {
// 鼠标移动时:隐藏遮挡条(变透明),方便操作
// 鼠标静止时:恢复遮挡条(变清晰),方便观看
const showBlocker = () => {
if (this.blurLayer) {
this.blurLayer.classList.remove('sb-hover-active');
}
};
const hideBlocker = () => {
if (this.blurLayer) {
this.blurLayer.classList.add('sb-hover-active');
}
};
container.addEventListener('mousemove', () => {
// 鼠标移动,说明用户想操作 -> 变透明
hideBlocker();
// 重置定时器
if (this.hoverTimeout) clearTimeout(this.hoverTimeout);
// 如果鼠标静止 2.5 秒,认为用户在观看 -> 恢复遮挡
this.hoverTimeout = setTimeout(() => {
// 只有当鼠标还在容器内时才恢复 (虽然 mouseleave 会处理移出,但这里双重保险)
// 实际上 mouseleave 已经处理了移出情况,这里主要处理“鼠标在视频上但不动”的情况
showBlocker();
}, 2500);
});
// 当鼠标离开视频播放器区域时,立即恢复遮挡条
container.addEventListener('mouseleave', () => {
if (this.hoverTimeout) clearTimeout(this.hoverTimeout);
showBlocker();
});
}
startAntiRemovalObserver(container) {
if (this.antiRemovalObserver) this.antiRemovalObserver.disconnect();
this.antiRemovalObserver = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.type === 'childList') {
for (const node of mutation.removedNodes) {
if (node === this.blockerHost) {
console.log('[Subtitle Blocker] Blocker was removed, re-injecting...');
// 重新注入
// 稍微延迟一下,避免与移除脚本发生死锁
setTimeout(() => {
if (this.blockerHost && !this.blockerHost.isConnected) {
container.appendChild(this.blockerHost);
}
}, 100);
}
}
}
}
});
this.antiRemovalObserver.observe(container, { childList: true });
}
removeBlocker() {
if (this.antiRemovalObserver) {
this.antiRemovalObserver.disconnect();
this.antiRemovalObserver = null;
}
if (this.blockerHost) {
this.blockerHost.remove();
this.blockerHost = null;
}
}
updateBlockerPosition() {
if (!this.activeVideo || !this.blockerHost || !this.blockerContainer) return;
// 如果容器就是视频的直接父级,且大小一致,直接铺满
// 但如果容器是更高层的播放器容器(如 YouTube #movie_player),它可能包含控制条等
// 我们需要确保遮挡层只覆盖在视频区域上,或者铺满整个播放器容器
// 对于 YouTube,#movie_player 的大小通常就是视频显示区域的大小(包括黑边)
// 所以铺满容器通常是安全的
this.blockerHost.style.top = '0';
this.blockerHost.style.left = '0';
this.blockerHost.style.width = '100%';
this.blockerHost.style.height = '100%';
// 计算模糊层的位置
// 我们基于容器的高度来计算,这样更稳定
const containerHeight = this.blockerContainer.offsetHeight;
// 重新计算 margin-bottom (保持比例)
const marginBottom = (containerHeight * this.config.bottomOffsetPercent) / 100;
this.blurLayer.style.marginBottom = `${marginBottom}px`;
}
handleFullscreenChange() {
// 全屏切换时,浏览器可能需要一点时间调整布局,延迟更新位置
setTimeout(() => {
this.updateBlockerPosition();
}, 100);
}
// --- 交互逻辑: 调整大小 (Resize) ---
startResize(e) {
e.preventDefault();
e.stopPropagation();
this.isResizing = true;
this.startY = e.clientY;
this.startHeight = this.blurLayer.offsetHeight;
document.body.style.cursor = 'ns-resize';
// 交互时强制显示
if (this.blurLayer) this.blurLayer.classList.add('sb-interacting');
}
// --- 交互逻辑: 拖拽位置 (Drag) ---
startDrag(e) {
// 只有在 Shift 模式下,或者点击的是之前的横条(已移除)才允许拖拽
// 现在我们依赖 pointer-events 控制,如果能触发 mousedown,说明 pointer-events 是 auto
// 即处于 Shift 模式,或者点击了 Resize Handle (但 Resize Handle 有自己的监听器并 stopPropagation)
// 确保不是点击了 Resize Handle (虽然 stopPropagation 应该阻止了,但双重保险)
if (e.target.classList.contains('sb-resize-handle')) return;
e.preventDefault();
e.stopPropagation();
this.isDragging = true;
this.startY = e.clientY;
// 获取当前的 margin-bottom 值
const style = window.getComputedStyle(this.blurLayer);
this.startBottom = parseInt(style.marginBottom, 10) || 0;
document.body.style.cursor = 'grabbing';
// 交互时强制显示
if (this.blurLayer) this.blurLayer.classList.add('sb-interacting');
}
handleMouseMove(e) {
if (!this.activeVideo) return;
const videoHeight = this.activeVideo.getBoundingClientRect().height;
if (this.isResizing) {
const deltaY = this.startY - e.clientY; // 向上拖动是增加高度
const newHeight = this.startHeight + deltaY;
// 限制高度范围 (最小 5%,最大 50%)
const minHeight = videoHeight * 0.05;
const maxHeight = videoHeight * 0.5;
if (newHeight >= minHeight && newHeight <= maxHeight) {
this.blurLayer.style.height = `${newHeight}px`;
// 更新配置中的百分比,以便缩放时保持比例
this.config.defaultHeightPercent = (newHeight / videoHeight) * 100;
}
}
if (this.isDragging) {
const deltaY = this.startY - e.clientY; // 向上拖动是增加底部距离
let newBottom = this.startBottom + deltaY;
// 动态计算最大底部距离 (视频高度 - 遮挡条高度)
// 这样可以允许遮挡条一直拖到最顶部
const blurLayerHeight = this.blurLayer.offsetHeight;
const minBottom = 0;
const maxBottom = videoHeight - blurLayerHeight;
// 使用 clamp 限制范围,确保能拖到边缘
newBottom = Math.max(minBottom, Math.min(newBottom, maxBottom));
this.blurLayer.style.marginBottom = `${newBottom}px`;
// 更新配置中的百分比
this.config.bottomOffsetPercent = (newBottom / videoHeight) * 100;
}
}
handleMouseUp() {
if (this.isResizing || this.isDragging) {
this.isResizing = false;
this.isDragging = false;
document.body.style.cursor = '';
// 交互结束,移除强制显示
if (this.blurLayer) this.blurLayer.classList.remove('sb-interacting');
// 保存调整后的位置和大小比例
chrome.storage.sync.set({
defaultHeightPercent: this.config.defaultHeightPercent,
bottomOffsetPercent: this.config.bottomOffsetPercent
});
}
}
}
// 启动插件
new SubtitleBlocker();