-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
1478 lines (1249 loc) · 40.5 KB
/
content.js
File metadata and controls
1478 lines (1249 loc) · 40.5 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
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
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 视频信息缓存助手 - 内容脚本
// Debug日志输出函数
function debugLog(...args) {
chrome.storage.local.get("settings", (data) => {
const settings = data.settings || { debugMode: false };
if (settings.debugMode) {
console.log("视频信息缓存助手:", ...args);
}
});
}
// 设置缓存视频数量 - 使用window对象保存以避免重复声明
if (typeof window.VIDEO_CACHE_COUNT === "undefined") {
window.VIDEO_CACHE_COUNT = Number.MAX_SAFE_INTEGER; // 无限制,缓存所有找到的视频
}
// 初始化全局去重集合
if (!window.globalProcessedUrls) {
window.globalProcessedUrls = new Set();
}
// 跟踪当前页面的视频数据,即使在快速刷新时也能保存
if (!window.currentPageVideos) {
window.currentPageVideos = [];
}
// 创建请求队列和防抖控制变量
if (!window.videoRequestQueue) {
window.videoRequestQueue = [];
window.isProcessingQueue = false;
window.lastExtractTime = 0;
window.pendingExtraction = false;
window.fastSaveMode = true; // 默认启用快速保存模式
}
// 立即检查快速保存模式设置
setTimeout(() => {
try {
chrome.runtime.sendMessage(
{ action: "checkFastSaveMode" },
function (response) {
if (response && response.fastSaveMode !== undefined) {
window.fastSaveMode = response.fastSaveMode;
debugLog("快速保存模式设置为", window.fastSaveMode);
}
}
);
} catch (e) {
debugLog("检查快速保存模式失败", e);
}
}, 500);
// 添加防抖函数
function debounce(fn, delay) {
let timer = null;
return function (...args) {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
timer = null;
}, delay);
};
}
// 添加节流函数
function throttle(fn, delay) {
let lastCall = 0;
return function (...args) {
const now = Date.now();
if (now - lastCall >= delay) {
fn.apply(this, args);
lastCall = now;
}
};
}
// 创建一个同步存储视频数据的函数
function fastSaveCurrentVideos() {
if (!window.currentPageVideos || window.currentPageVideos.length === 0) {
return;
}
try {
const videosToSave = [...window.currentPageVideos];
debugLog(
"执行快速保存操作,缓存视频数量:",
videosToSave.length
);
// 防止重复保存
window.currentPageVideos = [];
// 使用同步请求确保数据发送
const xhr = new XMLHttpRequest();
xhr.open("POST", chrome.runtime.getURL("/_empty_"), false); // 同步请求
xhr.setRequestHeader("Content-Type", "application/json");
try {
xhr.send(
JSON.stringify({
action: "saveVideos",
videos: videosToSave,
fastSave: true,
})
);
} catch (e) {
// 忽略网络错误,这是预期的
}
// 同时尝试使用消息API发送
chrome.runtime.sendMessage(
{
action: "saveVideos",
videos: videosToSave,
fastSave: true,
},
() => {}
);
} catch (e) {
debugLog("快速保存失败", e);
}
}
// 使用MutationObserver监控DOM变化,以检测页面即将刷新的迹象
function setupFastSaveObserver() {
// 监控<html>或<body>元素的移除,这通常发生在页面刷新或导航时
const fastSaveObserver = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.removedNodes.length > 0) {
// 检测到重大DOM变化,可能是页面即将刷新或导航
if (window.currentPageVideos.length > 0) {
debugLog("检测到DOM大量移除,尝试快速保存");
fastSaveCurrentVideos();
break;
}
}
}
});
// 监视整个文档的变化
fastSaveObserver.observe(document.documentElement, {
childList: true,
subtree: true,
});
}
// 添加页面类型检测函数
function isHomePage() {
const url = window.location.href;
// B站首页判断
if (url.includes("bilibili.com")) {
// B站首页URL模式
return (
url === "https://www.bilibili.com/" ||
url === "https://bilibili.com/" ||
url.match(/^https?:\/\/(www\.)?bilibili\.com\/?(\?.*)?$/)
);
}
// YouTube首页判断
if (url.includes("youtube.com")) {
// YouTube首页URL模式
return (
url === "https://www.youtube.com/" ||
url === "https://youtube.com/" ||
url.match(/^https?:\/\/(www\.)?youtube\.com\/?(\?.*)?$/)
);
}
return false;
}
// 修改安全执行函数,添加首页检测逻辑
function safeExecution(fn, ...args) {
// 只在首页执行视频提取
if (!isHomePage()) {
debugLog("非首页,停止缓存");
return;
}
if (isExtensionContextValid()) {
return fn.apply(this, args);
}
}
// 在页面加载完成后执行初始提取
window.addEventListener("load", () => {
debugLog("页面加载完成,检查是否为首页");
// 检查是否为首页
if (!isHomePage()) {
debugLog("非首页,不初始化提取功能");
return;
}
debugLog("检测到首页,准备提取视频信息");
// 立即执行一次提取,确保基本视频信息被捕获
setTimeout(() => safeExecution(extractVideoInfo), 300);
// 设置更精确的内容变化监听
setupTargetedContentObservers();
// 设置快速保存观察器
setupFastSaveObserver();
// 监听页面卸载前的各种事件
setupPageExitListeners();
});
// 设置页面退出相关的监听器
function setupPageExitListeners() {
// beforeunload事件 - 页面即将卸载
window.addEventListener("beforeunload", () => {
debugLog("页面即将卸载,尝试保存视频数据");
fastSaveCurrentVideos();
});
// unload事件 - 页面正在卸载
window.addEventListener("unload", () => {
debugLog("页面正在卸载,执行最后的保存尝试");
fastSaveCurrentVideos();
});
// pagehide事件 - 页面隐藏(更可靠地检测页面离开)
window.addEventListener("pagehide", () => {
debugLog("页面隐藏,执行保存");
fastSaveCurrentVideos();
});
// 监听浏览器性能事件
try {
if (window.performance && window.performance.getEntriesByType) {
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.entryType === "navigation" && entry.type === "reload") {
debugLog("检测到导航刷新,执行保存");
fastSaveCurrentVideos();
}
}
});
observer.observe({ entryTypes: ["navigation"] });
}
} catch (e) {
debugLog("性能观察器设置失败", e);
}
// 周期性保存检查
setInterval(() => {
if (window.currentPageVideos.length > 0 && window.fastSaveMode) {
debugLog(
"执行周期性保存,当前视频数量:",
window.currentPageVideos.length
);
fastSaveCurrentVideos();
}
}, 5000); // 每5秒检查一次
}
// 修改setupTargetedContentObservers函数,在设置观察器前检查是否为首页
function setupTargetedContentObservers() {
// 首先检查是否为首页
if (!isHomePage()) {
debugLog("非首页,不设置内容监听");
return;
}
debugLog("设置针对性内容监听");
// 记录找到的容器元素,用于调试
window.monitoredContainers = {
bilibili: null,
youtube: null,
};
// 使用防抖处理B站视频提取
const debouncedBilibiliExtract = debounce(() => {
debugLog("执行防抖后的B站视频提取");
extractBilibiliV8Videos();
}, 300);
// 使用防抖处理YouTube视频提取
const debouncedYoutubeExtract = debounce(() => {
debugLog("执行防抖后的YouTube视频提取");
extractYouTubeTargetedVideos();
}, 300);
// 创建针对B站版本8容器的专用观察器
const biliBiliV8Observer = new MutationObserver((mutations) => {
let hasRelevantChanges = false;
for (const mutation of mutations) {
if (mutation.addedNodes.length > 0) {
for (const node of mutation.addedNodes) {
if (node.nodeType !== Node.ELEMENT_NODE) continue;
const isVideoCard =
(node.classList &&
(node.classList.contains("bili-video-card") ||
node.classList.contains("feed-card"))) ||
node.querySelector?.(".bili-video-card, .feed-card");
if (isVideoCard) {
debugLog("检测到新增视频卡片:", node);
hasRelevantChanges = true;
window.pendingExtraction = true;
break;
}
}
}
if (hasRelevantChanges) break;
}
if (hasRelevantChanges) {
debugLog("检测到B站V8容器内视频变化,准备提取");
debouncedBilibiliExtract();
}
});
// 创建针对YouTube内容容器的专用观察器
const youtubeGridObserver = new MutationObserver((mutations) => {
debugLog("YouTube网格容器发生变化,分析变化类型");
let addedNodes = 0;
let hasRichItemAddition = false;
for (const mutation of mutations) {
if (mutation.addedNodes.length > 0) {
addedNodes += mutation.addedNodes.length;
const hasItems = Array.from(mutation.addedNodes).some((node) => {
if (node.nodeType !== Node.ELEMENT_NODE) return false;
const hasItem =
node.tagName === "YTD-RICH-ITEM-RENDERER" ||
node.querySelectorAll("ytd-rich-item-renderer").length > 0;
if (hasItem) {
debugLog("检测到新增YouTube视频项:", node);
window.pendingExtraction = true;
return true;
}
return false;
});
if (hasItems) {
hasRichItemAddition = true;
}
}
}
debugLog(
`YouTube容器变化统计 - 新增节点: ${addedNodes}, 含视频项: ${hasRichItemAddition}`
);
if (hasRichItemAddition || addedNodes > 3) {
debugLog(
"检测到YouTube网格容器内视频项变化,准备提取"
);
debouncedYoutubeExtract();
}
});
const documentObserver = new MutationObserver(() => {
if (location.href.includes("bilibili.com")) {
const targetContainer = document.querySelector(
".container.is-version8[data-v-3581b8d4]"
);
if (targetContainer && !targetContainer.hasAttribute("data-observed")) {
debugLog("找到目标B站V8容器,设置监听");
targetContainer.setAttribute("data-observed", "true");
processV8Container(targetContainer);
biliBiliV8Observer.observe(targetContainer, {
childList: true,
subtree: true,
attributes: false,
});
debugLog("目标容器监听已设置");
}
const generalContainer = document.querySelector(".container.is-version8");
if (
generalContainer &&
!generalContainer.hasAttribute("data-observed") &&
generalContainer !== targetContainer
) {
debugLog("找到一般B站V8容器,设置备用监听");
generalContainer.setAttribute("data-observed", "true");
biliBiliV8Observer.observe(generalContainer, {
childList: true,
subtree: true,
attributes: false,
});
}
}
if (location.href.includes("youtube.com")) {
const ytGridContainer = document.querySelector(
"div#contents.style-scope.ytd-rich-grid-renderer"
);
if (ytGridContainer && !ytGridContainer.getAttribute("data-observed")) {
debugLog(
"找到YouTube网格容器,设置专门监听:",
ytGridContainer
);
ytGridContainer.setAttribute("data-observed", "true");
window.monitoredContainers.youtube = ytGridContainer;
extractYouTubeTargetedVideos();
youtubeGridObserver.observe(ytGridContainer, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ["class", "style", "src", "data-src"],
});
debugLog("YouTube网格容器监听已设置完成");
} else if (!ytGridContainer) {
if (!window.youtubeContainerRetryCount) {
window.youtubeContainerRetryCount = 0;
}
if (window.youtubeContainerRetryCount < 10) {
window.youtubeContainerRetryCount++;
debugLog(
`未找到YouTube网格容器,将在1秒后重试(${window.youtubeContainerRetryCount}/10)`
);
setTimeout(() => {
const retryContainer = document.querySelector(
"div#contents.style-scope.ytd-rich-grid-renderer"
);
if (retryContainer) {
debugLog("重试成功,找到YouTube网格容器");
if (!retryContainer.getAttribute("data-observed")) {
retryContainer.setAttribute("data-observed", "true");
window.monitoredContainers.youtube = retryContainer;
extractYouTubeTargetedVideos();
youtubeGridObserver.observe(retryContainer, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ["class", "style", "src", "data-src"],
});
}
}
}, 1000);
}
}
}
});
documentObserver.observe(document.documentElement, {
childList: true,
subtree: true,
});
// 使用节流函数优化滚动处理
const throttledScrollHandler = throttle(() => {
if (location.href.includes("bilibili.com")) {
const container =
document.querySelector(".container.is-version8[data-v-3581b8d4]") ||
document.querySelector(".container.is-version8");
if (container) {
debugLog("滚动停止,重新检查容器内容");
window.pendingExtraction = true;
processV8Container(container);
}
} else if (location.href.includes("youtube.com")) {
window.pendingExtraction = true;
extractYouTubeTargetedVideos();
}
}, 800);
let scrollTimeout;
window.addEventListener("scroll", () => {
// 先检查是否为首页
if (!isHomePage()) {
return; // 非首页则直接返回,不处理滚动事件
}
if (scrollTimeout) clearTimeout(scrollTimeout);
scrollTimeout = setTimeout(() => {
throttledScrollHandler();
}, 1000);
});
document.addEventListener("visibilitychange", () => {
// 检查是否为首页
if (!isHomePage()) {
return; // 非首页则直接返回
}
if (document.visibilityState === "visible") {
debugLog("页面变为可见,检查是否有新内容");
if (location.href.includes("bilibili.com")) {
extractBilibiliV8Videos();
} else if (location.href.includes("youtube.com")) {
extractYouTubeTargetedVideos();
}
}
});
let lastUrl = location.href;
const urlCheckInterval = setInterval(() => {
if (location.href !== lastUrl) {
debugLog(`URL变化 ${lastUrl} -> ${location.href}`);
lastUrl = location.href;
document.querySelectorAll("[data-observed]").forEach((el) => {
el.removeAttribute("data-observed");
});
window.bilibiliContainerRetryCount = 0;
window.youtubeContainerRetryCount = 0;
window.monitoredContainers = {
bilibili: null,
youtube: null,
};
debugLog(
`当前URL缓存数量: ${window.globalProcessedUrls.size}`
);
setTimeout(() => {
if (location.href.includes("bilibili.com")) {
extractBilibiliV8Videos();
} else if (location.href.includes("youtube.com")) {
extractYouTubeTargetedVideos();
}
}, 1000);
}
}, 500);
// 监听F5键和浏览器刷新按钮
document.addEventListener("keydown", function (e) {
if (e.key === "F5" || (e.ctrlKey && e.key === "r")) {
debugLog("检测到刷新快捷键,执行快速保存");
fastSaveCurrentVideos();
}
});
// 监听鼠标右键菜单
document.addEventListener("contextmenu", function () {
// 右键菜单可能会导致刷新操作,预先保存
if (window.currentPageVideos.length > 0) {
debugLog("检测到右键菜单,预防性保存");
fastSaveCurrentVideos();
}
});
}
// 处理视频请求队列
function processVideoRequestQueue() {
if (window.isProcessingQueue || window.videoRequestQueue.length === 0) {
return;
}
window.isProcessingQueue = true;
const request = window.videoRequestQueue.shift();
debugLog(
`处理队列请求,当前队列长度: ${window.videoRequestQueue.length}`
);
sendMessageSafely(request.message, (response) => {
debugLog(`队列请求处理完成`, response);
window.isProcessingQueue = false;
// 延迟处理下一个请求
setTimeout(() => {
processVideoRequestQueue();
}, 100);
if (request.callback) {
request.callback(response);
}
});
}
// 优化的安全发送消息函数,加入队列机制
function sendMessageSafely(message, callback) {
try {
// 快速保存逻辑 - 对于saveVideos的请求
if (message.action === "saveVideos" && window.fastSaveMode) {
// 确保当前页面的视频集合包含这些视频
if (!message.isEmergency) {
const videosToAdd = message.videos.filter(
(v) =>
!window.currentPageVideos.some((existing) => existing.url === v.url)
);
if (videosToAdd.length > 0) {
window.currentPageVideos.push(...videosToAdd);
}
}
}
// 标准消息发送逻辑
chrome.runtime.sendMessage(message, (response) => {
if (!handleRuntimeError() && callback) {
callback(response);
}
});
} catch (error) {
debugLog("消息发送失败:", error);
// 如果是保存请求且在快速保存模式下,确保数据至少被本地保存
if (message.action === "saveVideos" && window.fastSaveMode) {
debugLog("尝试使用备用保存机制");
// 将视频添加到当前页面视频集合
window.currentPageVideos.push(...message.videos);
}
}
}
// 优化B站数据提取函数,添加紧急模式参数
function extractCardsAndSave(cards, isEmergency = false) {
debugLog(
`开始提取 ${cards.length} 个元素的信息${
isEmergency ? "(紧急模式)" : ""
}`
);
const videos = [];
const processedUrls = new Set();
// 在紧急模式下提高处理效率
const maxCardsToProcess = isEmergency
? cards.length
: Math.min(cards.length, 50);
for (let i = 0; i < maxCardsToProcess; i++) {
try {
const card = cards[i];
let linkElement = null;
if (card.classList && card.classList.contains("bili-video-card")) {
linkElement = card.querySelector(".bili-video-card__image--link");
if (!linkElement) {
linkElement = card.querySelector('a[href*="/video/"]');
}
} else if (card.classList && card.classList.contains("feed-card")) {
linkElement = card.querySelector('a[href*="/video/"]');
} else if (
card.tagName === "A" &&
card.href &&
card.href.includes("/video/")
) {
linkElement = card;
} else {
linkElement = card.querySelector('a[href*="/video/"]');
}
if (!linkElement || !linkElement.href) continue;
let url;
try {
url = new URL(linkElement.href, location.origin).href.split("?")[0];
} catch (e) {
continue;
}
if (processedUrls.has(url) || window.globalProcessedUrls?.has(url))
continue;
processedUrls.add(url);
if (window.globalProcessedUrls) window.globalProcessedUrls.add(url);
const videoInfo = extractVideoInfoFromElement(card, linkElement, url);
if (videoInfo) {
videos.push(videoInfo);
// 重要:同时添加到当前页面视频集合,便于快速保存
if (window.fastSaveMode && !isEmergency) {
window.currentPageVideos.push(videoInfo);
}
}
} catch (error) {
debugLog("处理单个卡片时出错", error);
}
}
debugLog(`成功提取 ${videos.length} 个视频信息`);
// 如果是紧急模式,立即执行快速保存并启动标准保存
if (isEmergency) {
// 添加到当前页面视频集合
window.currentPageVideos.push(...videos);
fastSaveCurrentVideos();
}
if (videos.length > 0) {
sendMessageSafely(
{
action: "saveVideos",
videos,
isEmergency: isEmergency,
},
(response) => {
debugLog(
`已发送 ${videos.length} 个B站视频信息:`,
response
);
}
);
}
}
// 处理V8容器的优化函数,添加紧急模式参数
function processV8Container(container, isEmergency = false) {
debugLog(
`处理V8容器中的视频卡片${
isEmergency ? "(紧急模式)" : ""
}`
);
// 在紧急模式下使用更宽松的选择器直接提取
if (isEmergency) {
const allVideoCards = container.querySelectorAll(
".bili-video-card, .feed-card"
);
const videoLinks = container.querySelectorAll('a[href*="/video/"]');
debugLog(
`紧急模式找到 ${allVideoCards.length} 个卡片和 ${videoLinks.length} 个链接`
);
if (allVideoCards.length > 0) {
extractCardsAndSave(Array.from(allVideoCards), true);
return;
}
if (videoLinks.length > 0) {
extractCardsAndSave(Array.from(videoLinks), true);
return;
}
}
const feedCards = container.querySelectorAll(
"div[data-v-3581b8d4].feed-card"
);
const videoCards = container.querySelectorAll(
"div[data-v-3581b8d4].bili-video-card.is-rcmd.enable-no-interest"
);
debugLog(
`精确匹配找到 ${feedCards.length} 个feed-card和 ${videoCards.length} 个bili-video-card`
);
if (feedCards.length + videoCards.length < 5) {
debugLog("精确匹配找到的卡片数量不足,使用宽松选择器");
const relaxedFeedCards = container.querySelectorAll(".feed-card");
const relaxedVideoCards = container.querySelectorAll(
".bili-video-card.is-rcmd.enable-no-interest"
);
const allVideoCards = container.querySelectorAll(".bili-video-card");
debugLog(
`宽松选择器找到 ${relaxedFeedCards.length} 个feed-card, ` +
`${relaxedVideoCards.length} 个特定bili-video-card, ` +
`${allVideoCards.length} 个一般bili-video-card`
);
const allCards = [
...Array.from(feedCards),
...Array.from(videoCards),
...Array.from(relaxedFeedCards),
...Array.from(relaxedVideoCards),
];
if (allCards.length < 5 && allVideoCards.length > 0) {
allCards.push(...Array.from(allVideoCards));
}
const uniqueCards = Array.from(new Set(allCards));
debugLog(
`去重后共有 ${uniqueCards.length} 个卡片待处理`
);
if (uniqueCards.length > 0) {
extractCardsAndSave(uniqueCards);
return;
}
} else {
const cards = [...Array.from(feedCards), ...Array.from(videoCards)];
debugLog(
`精确匹配找到 ${cards.length} 个卡片,开始处理`
);
extractCardsAndSave(cards);
return;
}
debugLog("常规方法未找到足够卡片,使用视频链接选择器");
const videoLinks = container.querySelectorAll('a[href*="/video/"]');
if (videoLinks.length > 0) {
debugLog(`找到 ${videoLinks.length} 个视频链接`);
extractCardsAndSave(Array.from(videoLinks));
return;
}
debugLog("所有方法均未找到视频卡片,尝试检查整个DOM树");
console.log("容器内部HTML结构片段:", container.innerHTML.substring(0, 1000));
const potentialElements = findPotentialVideoElements(container);
if (potentialElements.length > 0) {
debugLog(
`通过DOM遍历找到 ${potentialElements.length} 个潜在视频元素`
);
extractCardsAndSave(potentialElements);
} else {
debugLog("无法找到任何视频元素");
}
}
// 优化YouTube备用元素提取,添加紧急模式
function extractYouTubeBackupElements(elements, isEmergency = false) {
const videos = [];
const processedUrls = new Set();
debugLog(
`开始从YouTube备用元素提取视频,共 ${
elements.length
} 个元素${isEmergency ? "(紧急模式)" : ""}`
);
// 在紧急模式下提高处理效率
const maxElementsToProcess = isEmergency
? elements.length
: Math.min(elements.length, 50);
for (let i = 0; i < maxElementsToProcess; i++) {
try {
const element = elements[i];
let linkElement = null;
if (element.tagName === "A" && element.id === "thumbnail") {
linkElement = element;
} else {
linkElement =
element.querySelector("a#thumbnail") ||
element.querySelector("a[href*='watch?v=']");
}
if (!linkElement || !linkElement.href) continue;
let url = linkElement.href.split("&")[0];
// 支持普通视频和Shorts短视频
const isShorts = url.includes("/shorts/");
const isWatch = url.includes("watch?v=");
if (!isWatch && !isShorts) continue;
// 不再使用去重逻辑,允许覆盖旧视频
// if (window.globalProcessedUrls.has(url) || processedUrls.has(url)) {
// continue;
// }
processedUrls.add(url);
if (window.globalProcessedUrls) window.globalProcessedUrls.add(url);
// 提取视频ID
let videoId;
if (isShorts) {
const match = url.match(/\/shorts\/([^/?]+)/);
videoId = match ? match[1] : null;
} else {
videoId = url.split("watch?v=")[1];
}
if (!videoId) continue;
let title = "";
let titleElement = null;
// 尝试多种方式查找标题元素
const titleSelectors = [
"#video-title",
"yt-formatted-string#video-title",
"[id='video-title']",
"h3 a",
"h3",
"[id*='title']",
];
// 首先在element内部查找
for (const selector of titleSelectors) {
titleElement = element.querySelector(selector);
if (titleElement && titleElement.textContent.trim()) {
title = titleElement.textContent.trim();
break;
}
}
// 如果没找到,在父元素中查找
if (!title && element.parentElement) {
for (const selector of titleSelectors) {
titleElement = element.parentElement.querySelector(selector);
if (titleElement && titleElement.textContent.trim()) {
title = titleElement.textContent.trim();
break;
}
}
}
// 尝试通过linkElement的属性获取
if (!title && linkElement) {
if (linkElement.getAttribute("aria-label")) {
title = linkElement.getAttribute("aria-label").trim();
} else if (linkElement.getAttribute("title")) {
title = linkElement.getAttribute("title").trim();
}
}
// 最后的兜底:使用视频ID作为标题
if (!title) {
title = isShorts ? `YouTube Shorts: ${videoId}` : `YouTube Video: ${videoId}`;
}
// 使用当前数组的索引作为原始位置
const originalPosition = videos.length;
videos.push({
title: title,
url: url,
thumbnail: `https://i.ytimg.com/vi/${videoId}/hqdefault.jpg`,
source: "youtube",
originalPosition,
isShorts: isShorts,
});
} catch (error) {
debugLog("处理YouTube备用元素时出错", error);
}
}
debugLog(
`从备用元素中提取出 ${videos.length} 个YouTube视频`
);
if (videos.length > 0) {
sendMessageSafely(
{
action: "saveVideos",
videos,
isEmergency: isEmergency,
},
(response) => {
debugLog(
`已保存 ${videos.length} 个YouTube备用视频:`,
response
);
}
);
}
}
// 优化YouTube网格视频提取函数,添加紧急模式
function extractYouTubeGridVideos(gridItems, maxCount, isEmergency = false) {
const videos = [];
const processedUrls = new Set();
debugLog(
`开始从YouTube网格提取${gridItems.length}条视频${
isEmergency ? "(紧急模式)" : ""
}`
);
// 在紧急模式下提高处理效率
const maxItemsToProcess = isEmergency
? gridItems.length
: Math.min(gridItems.length, 50);
for (let i = 0; i < maxItemsToProcess; i++) {
try {
const gridItem = gridItems[i];
// 尝试多种方式查找链接元素
let linkElement = null;
// 方法1: 通过 ytd-rich-grid-media 容器查找
const videoContainer = gridItem.querySelector("ytd-rich-grid-media");
if (videoContainer) {
linkElement = videoContainer.querySelector("a#thumbnail");
}