-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
980 lines (835 loc) · 36.7 KB
/
background.js
File metadata and controls
980 lines (835 loc) · 36.7 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
class RefreshService {
constructor() {
// 常量定义
this.MAX_RETRY_ATTEMPTS = 3;
this.MAX_ERROR_COUNT = 10; // 最大错误次数,超过后自动停止
this.MAX_HEALTH_CHECK_ERROR_COUNT = 20; // 健康检查最大错误次数
this.HEALTH_CHECK_INTERVAL = 5 * 60 * 1000; // 5分钟
this.NOTIFICATION_THROTTLE = 60 * 1000; // 通知节流:1分钟
this.NOTIFICATION_CLEANUP_AGE = 24 * 60 * 60 * 1000; // 24小时
this.ERROR_BACKOFF_MULTIPLIER = 0.2; // 错误退避倍数
this.MAX_BACKOFF_MULTIPLIER = 5; // 最大退避倍数
this.TAB_LOAD_TIMEOUT = 5000; // 标签页加载超时:5秒
this.RESTORE_DELAY_MAX = 5000; // 恢复状态最大延迟:5秒
this.activeRefreshers = new Map(); // tabId -> refresher config
this.timers = new Map(); // tabId -> timer id
this.healthCheckInterval = null;
this.maxRetryAttempts = this.MAX_RETRY_ATTEMPTS;
this.isShuttingDown = false;
this.isEdge = this.detectEdge();
this.iconState = new Map(); // tabId -> icon state (normal/gray)
console.log(`🌐 检测到浏览器: ${this.isEdge ? 'Microsoft Edge' : 'Google Chrome'}`);
// Edge特定初始化
if (this.isEdge) {
this.initEdgeCompatibility();
}
// 初始化图标状态
this.initIconManagement();
// 监听消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
this.handleMessage(message, sender, sendResponse);
return true; // 保持消息通道开放
});
// 监听标签页更新和关闭
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete' && this.activeRefreshers.has(tabId)) {
this.handleTabUpdated(tabId, tab);
}
});
chrome.tabs.onRemoved.addListener((tabId) => {
this.stopRefresh(tabId);
});
// 监听扩展暂停/恢复
chrome.runtime.onSuspend.addListener(() => {
this.handleSuspend();
});
chrome.runtime.onStartup.addListener(() => {
this.handleStartup();
});
// 扩展启动时恢复状态
this.restoreState();
// 启动健康检查
this.startHealthCheck();
}
async handleMessage(message, sender, sendResponse) {
console.log('🔵 收到消息:', message);
try {
switch (message.action) {
case 'startRefresh':
console.log('🚀 开始启动刷新器 - TabId:', message.tabId, 'Settings:', message.settings);
await this.startRefresh(message.tabId, message.settings);
console.log('✅ 刷新器启动成功 - TabId:', message.tabId);
sendResponse({ success: true });
break;
case 'stopRefresh':
const tabIdToStop = message.tabId || sender.tab?.id;
console.log('🛑 停止刷新器 - TabId:', tabIdToStop);
await this.stopRefresh(tabIdToStop);
console.log('✅ 刷新器停止成功 - TabId:', tabIdToStop);
sendResponse({ success: true });
break;
case 'getStatus':
const tabIdForStatus = message.tabId || sender.tab?.id;
const status = this.getRefreshStatus(tabIdForStatus);
console.log('📊 获取状态 - TabId:', tabIdForStatus, 'Status:', status);
sendResponse({ success: true, data: status });
break;
case 'healthCheck':
console.log('❤️ 健康检查 - 活跃刷新器数量:', this.activeRefreshers.size);
sendResponse({ success: true, health: 'ok', activeCount: this.activeRefreshers.size });
break;
default:
console.log('❌ 未知操作:', message.action);
sendResponse({ success: false, error: 'Unknown action' });
}
} catch (error) {
console.error('💥 处理消息时出错:', error);
sendResponse({ success: false, error: error.message });
}
}
async startRefresh(tabId, settings) {
// 停止已存在的刷新器
this.stopRefresh(tabId);
// 验证设置
if (!this.validateSettings(settings)) {
throw new Error('无效的设置参数');
}
// 创建新的刷新器配置
const refresher = {
tabId,
settings,
refreshCount: 0,
errorCount: 0,
lastErrorTime: null,
startTime: Date.now(),
nextRefreshTime: null,
isActive: true,
retryAttempts: 0
};
this.activeRefreshers.set(tabId, refresher);
// 保存到存储(立即保存)
await this.saveRefresherState(tabId, refresher, true);
// 更新图标显示运行状态
await this.updateIconForTab(tabId).catch((err) => {
console.warn(`启动刷新时更新图标失败 (TabId: ${tabId}):`, err.message);
});
// 调度下次刷新
this.scheduleNextRefresh(tabId);
console.log(`开始刷新标签页 ${tabId}`, settings);
}
validateSettings(settings) {
if (!settings || typeof settings !== 'object') return false;
if (!['fixed', 'random'].includes(settings.mode)) return false;
// 验证时间单位
if (!['seconds', 'minutes'].includes(settings.minTimeUnit)) return false;
// 验证最小时间
if (!Number.isInteger(settings.minTime) || settings.minTime < 1) return false;
const minMaxValue = settings.minTimeUnit === 'seconds' ? 3600 : 60;
if (settings.minTime > minMaxValue) return false;
// 验证随机模式的最大时间
if (settings.mode === 'random') {
if (!['seconds', 'minutes'].includes(settings.maxTimeUnit)) return false;
if (!Number.isInteger(settings.maxTime) || settings.maxTime < 1) return false;
const maxMaxValue = settings.maxTimeUnit === 'seconds' ? 3600 : 60;
if (settings.maxTime > maxMaxValue) return false;
// 转换为秒进行比较
const minTimeInSeconds = settings.minTimeUnit === 'seconds' ? settings.minTime : settings.minTime * 60;
const maxTimeInSeconds = settings.maxTimeUnit === 'seconds' ? settings.maxTime : settings.maxTime * 60;
if (maxTimeInSeconds < minTimeInSeconds) return false;
}
return true;
}
async stopRefresh(tabId) {
if (!tabId) return;
try {
// 清除定时器
if (this.timers.has(tabId)) {
clearTimeout(this.timers.get(tabId));
this.timers.delete(tabId);
}
// 移除刷新器
this.activeRefreshers.delete(tabId);
// 清除图标状态
this.iconState.delete(tabId);
// 清除防抖定时器
if (this.saveTimers && this.saveTimers.has(tabId)) {
clearTimeout(this.saveTimers.get(tabId));
this.saveTimers.delete(tabId);
}
// 清除存储
await this.clearRefresherState(tabId);
// 更新图标,移除运行状态badge
await this.updateIconForTab(tabId).catch((err) => {
// 标签页可能已关闭,这是正常情况
console.log(`停止刷新时更新图标失败 (TabId: ${tabId}):`, err.message);
});
console.log(`停止刷新标签页 ${tabId}`);
} catch (error) {
console.error(`停止刷新时出错:`, error);
}
}
scheduleNextRefresh(tabId) {
const refresher = this.activeRefreshers.get(tabId);
if (!refresher || !refresher.isActive || this.isShuttingDown) return;
const { settings } = refresher;
let delay = this.calculateDelay(settings);
// 如果有错误历史,增加延迟(错误退避算法)
if (refresher.errorCount > 0) {
const backoffMultiplier = Math.min(refresher.errorCount, this.MAX_BACKOFF_MULTIPLIER);
delay *= (1 + backoffMultiplier * this.ERROR_BACKOFF_MULTIPLIER);
}
// Edge兼容性:增加额外的缓冲时间
if (this.isEdge && this.edgeTimerBuffer) {
delay += this.edgeTimerBuffer;
console.log(`🔧 Edge模式:添加 ${this.edgeTimerBuffer}ms 缓冲时间`);
}
refresher.nextRefreshTime = Date.now() + delay;
// 发送状态更新到popup
this.notifyPopup(tabId, {
nextRefreshTime: refresher.nextRefreshTime,
refreshCount: refresher.refreshCount,
errorCount: refresher.errorCount,
startTime: refresher.startTime
});
// 设置定时器
const timerId = setTimeout(() => {
this.performRefresh(tabId);
}, delay);
this.timers.set(tabId, timerId);
console.log(`⏰ 已调度标签页 ${tabId} 在 ${Math.round(delay/1000)}秒 后刷新 (${new Date(refresher.nextRefreshTime).toLocaleTimeString()})`);
console.log(`📋 当前活跃定时器数量: ${this.timers.size}, 活跃刷新器数量: ${this.activeRefreshers.size}`);
}
calculateDelay(settings) {
if (settings.mode === 'fixed') {
// 根据时间单位转换为毫秒
const multiplier = settings.minTimeUnit === 'seconds' ? 1000 : 60 * 1000;
return settings.minTime * multiplier;
} else {
// 随机模式 - 转换为毫秒
const minMultiplier = settings.minTimeUnit === 'seconds' ? 1000 : 60 * 1000;
const maxMultiplier = settings.maxTimeUnit === 'seconds' ? 1000 : 60 * 1000;
const minMs = settings.minTime * minMultiplier;
const maxMs = settings.maxTime * maxMultiplier;
return Math.floor(Math.random() * (maxMs - minMs + 1)) + minMs;
}
}
async performRefresh(tabId) {
console.log(`🔄 开始执行刷新 - TabId: ${tabId}`);
const refresher = this.activeRefreshers.get(tabId);
if (!refresher || !refresher.isActive || this.isShuttingDown) {
console.log(`⚠️ 刷新器不存在或已停止 - TabId: ${tabId}, refresher:`, refresher ? 'exists' : 'not found', 'isActive:', refresher?.isActive, 'isShuttingDown:', this.isShuttingDown);
return;
}
let success = false;
let retryCount = 0;
const maxRetries = 3;
while (!success && retryCount < maxRetries) {
try {
console.log(`🔍 检查标签页 - TabId: ${tabId} (尝试 ${retryCount + 1}/${maxRetries})`);
// 检查标签页是否仍然存在和可访问
const tab = await this.getTabWithRetry(tabId, 2);
if (!tab || !this.isValidTab(tab)) {
console.log(`❌ 标签页 ${tabId} 不存在或无效,停止刷新`, tab ? `URL: ${tab.url}` : '标签页为空');
this.stopRefresh(tabId);
return;
}
console.log(`🔄 执行刷新 - TabId: ${tabId}, URL: ${tab.url}`);
// 执行刷新 - Edge兼容模式
if (this.isEdge) {
const edgeSuccess = await this.performRefreshEdgeCompatible(tabId);
if (!edgeSuccess) {
throw new Error('Edge兼容模式刷新失败');
}
} else {
await chrome.tabs.reload(tabId);
}
console.log(`⏳ 等待页面加载完成 - TabId: ${tabId}`);
// 等待页面加载完成(可选,避免刷新过于频繁)
await this.waitForTabLoad(tabId, 5000);
// 更新计数
refresher.refreshCount++;
refresher.errorCount = Math.max(0, refresher.errorCount - 1); // 成功后减少错误计数
refresher.retryAttempts = 0;
// 使用防抖保存,避免频繁写入
await this.saveRefresherState(tabId, refresher, false);
// 发送通知 - Edge兼容模式
if (refresher.settings.notificationEnabled) {
if (this.isEdge) {
await this.showNotificationEdgeCompatible(tabId, refresher.refreshCount);
} else {
await this.showNotification(tabId, refresher.refreshCount);
}
}
// 发送状态更新到popup
this.notifyPopup(tabId, {
refreshCount: refresher.refreshCount,
errorCount: refresher.errorCount,
startTime: refresher.startTime
});
// 自动刷新不再播放提示音(浏览器限制)
// 提示音功能仅在手动立即刷新时可用
console.log(`✅ 已刷新标签页 ${tabId},第 ${refresher.refreshCount} 次`);
success = true;
} catch (error) {
retryCount++;
refresher.errorCount++;
refresher.lastErrorTime = Date.now();
console.error(`💥 刷新标签页 ${tabId} 时出错 (尝试 ${retryCount}/${maxRetries}):`, error);
if (retryCount < maxRetries) {
console.log(`⏳ 等待 ${retryCount} 秒后重试...`);
// 等待后重试
await new Promise(resolve => setTimeout(resolve, 1000 * retryCount));
}
}
}
if (!success) {
console.error(`标签页 ${tabId} 刷新失败,达到最大重试次数`);
// 设置错误图标
await this.setErrorIcon();
// 检查是否应该停止(连续失败过多)
if (refresher.errorCount >= this.MAX_ERROR_COUNT) {
console.log(`标签页 ${tabId} 错误次数达到上限(${this.MAX_ERROR_COUNT}),自动停止刷新`);
this.stopRefresh(tabId);
return;
}
} else {
// 刷新成功,确保图标状态正确
await this.updateIconForTab(tabId).catch((err) => {
console.log(`刷新成功后更新图标失败 (TabId: ${tabId}):`, err.message);
});
}
// 调度下次刷新(无论成功还是失败都继续)
if (refresher.isActive) {
this.scheduleNextRefresh(tabId);
}
}
async getTabWithRetry(tabId, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
const tab = await chrome.tabs.get(tabId);
return tab;
} catch (error) {
if (i === maxRetries - 1) {
console.error(`获取标签页 ${tabId} 失败,已重试 ${maxRetries} 次:`, error);
throw error;
}
// 指数退避
await new Promise(resolve => setTimeout(resolve, 500 * (i + 1)));
}
}
}
isValidTab(tab) {
if (!tab) return false;
if (tab.url.startsWith('chrome://') || tab.url.startsWith('edge://') || tab.url.startsWith('moz-extension://')) return false;
return true;
}
async waitForTabLoad(tabId, timeout = 5000) {
return new Promise((resolve) => {
let listener = null;
const cleanup = () => {
if (listener) {
chrome.tabs.onUpdated.removeListener(listener);
listener = null;
}
};
const timeoutId = setTimeout(() => {
cleanup();
resolve();
}, timeout);
listener = (updatedTabId, changeInfo) => {
if (updatedTabId === tabId && changeInfo.status === 'complete') {
clearTimeout(timeoutId);
cleanup();
resolve();
}
};
chrome.tabs.onUpdated.addListener(listener);
});
}
async showNotification(tabId, refreshCount) {
try {
const tab = await chrome.tabs.get(tabId);
const title = tab.title || '未知页面';
// 限制通知频率,避免过多通知
const lastNotificationKey = `lastNotification_${tabId}`;
const lastNotificationTime = await chrome.storage.local.get(lastNotificationKey);
const now = Date.now();
// 通知节流:避免过于频繁的通知
if (lastNotificationTime[lastNotificationKey] &&
now - lastNotificationTime[lastNotificationKey] < this.NOTIFICATION_THROTTLE) {
return;
}
await chrome.storage.local.set({ [lastNotificationKey]: now });
chrome.notifications.create(`refresh_${tabId}_${now}`, {
type: 'basic',
iconUrl: 'icons/icon48.png',
title: '页面已刷新',
message: `${title}\n刷新次数: ${refreshCount}`,
priority: 0 // 低优先级,避免打扰用户
});
} catch (error) {
console.error('显示通知时出错:', error);
// 通知失败不影响刷新功能
}
}
notifyPopup(tabId, data) {
// 向popup发送状态更新
chrome.runtime.sendMessage({
action: 'updateStatus',
tabId,
data
}).catch(() => {
// popup可能未打开,忽略错误
});
}
getRefreshStatus(tabId) {
const refresher = this.activeRefreshers.get(tabId);
if (!refresher) {
return { isActive: false };
}
return {
isActive: refresher.isActive,
refreshCount: refresher.refreshCount,
errorCount: refresher.errorCount,
startTime: refresher.startTime,
nextRefreshTime: refresher.nextRefreshTime,
settings: refresher.settings
};
}
async saveRefresherState(tabId, refresher, immediate = false) {
try {
const key = `refresher_${tabId}`;
const stateData = {
settings: refresher.settings,
refreshCount: refresher.refreshCount,
errorCount: refresher.errorCount || 0,
startTime: refresher.startTime,
isActive: refresher.isActive
};
// 使用防抖机制,避免频繁写入storage
if (!immediate) {
if (this.saveTimers) {
clearTimeout(this.saveTimers.get(tabId));
} else {
this.saveTimers = new Map();
}
this.saveTimers.set(tabId, setTimeout(async () => {
await chrome.storage.local.set({ [key]: stateData });
this.saveTimers.delete(tabId);
}, 1000)); // 1秒后保存
} else {
// 立即保存(用于启动和停止时)
await chrome.storage.local.set({ [key]: stateData });
}
} catch (error) {
console.error('保存状态时出错:', error);
}
}
async clearRefresherState(tabId) {
try {
const key = `refresher_${tabId}`;
await chrome.storage.local.remove([key, `lastNotification_${tabId}`]);
} catch (error) {
console.error('清除状态时出错:', error);
}
}
async restoreState() {
try {
// 获取所有存储的刷新器状态
const storage = await chrome.storage.local.get();
const refresherKeys = Object.keys(storage).filter(key => key.startsWith('refresher_'));
console.log(`恢复 ${refresherKeys.length} 个刷新器状态`);
for (const key of refresherKeys) {
const tabId = parseInt(key.replace('refresher_', ''));
const savedState = storage[key];
// 检查标签页是否仍然存在
try {
const tab = await chrome.tabs.get(tabId);
if (tab && savedState.isActive && this.isValidTab(tab)) {
// 恢复刷新器
const refresher = {
tabId,
settings: savedState.settings,
refreshCount: savedState.refreshCount || 0,
errorCount: savedState.errorCount || 0,
lastErrorTime: null,
startTime: savedState.startTime,
nextRefreshTime: null,
isActive: true,
retryAttempts: 0
};
this.activeRefreshers.set(tabId, refresher);
// 延迟启动,避免同时启动过多定时器
setTimeout(() => {
this.scheduleNextRefresh(tabId);
}, Math.random() * this.RESTORE_DELAY_MAX);
console.log(`恢复标签页 ${tabId} 的刷新状态`);
} else {
// 清除无效状态
await this.clearRefresherState(tabId);
}
} catch (error) {
// 标签页不存在,清除状态
await this.clearRefresherState(tabId);
}
}
} catch (error) {
console.error('恢复状态时出错:', error);
}
}
handleTabUpdated(tabId, tab) {
const refresher = this.activeRefreshers.get(tabId);
if (refresher && tab.status === 'complete') {
// 标签页加载完成,可能需要更新UI状态
this.notifyPopup(tabId, {
refreshCount: refresher.refreshCount,
errorCount: refresher.errorCount,
nextRefreshTime: refresher.nextRefreshTime,
startTime: refresher.startTime
});
}
}
// 健康检查机制
startHealthCheck() {
// 定期进行健康检查
this.healthCheckInterval = setInterval(() => {
this.performHealthCheck();
}, this.HEALTH_CHECK_INTERVAL);
}
async performHealthCheck() {
try {
console.log(`健康检查: 活跃刷新器数量 ${this.activeRefreshers.size}`);
// 检查每个活跃的刷新器
for (const [tabId, refresher] of this.activeRefreshers.entries()) {
try {
const tab = await chrome.tabs.get(tabId);
if (!tab || !this.isValidTab(tab)) {
console.log(`健康检查: 清理无效标签页 ${tabId}`);
this.stopRefresh(tabId);
continue;
}
// 检查是否有定时器
if (!this.timers.has(tabId)) {
console.log(`健康检查: 重新调度标签页 ${tabId}`);
this.scheduleNextRefresh(tabId);
}
// 检查错误率
if (refresher.errorCount > this.MAX_HEALTH_CHECK_ERROR_COUNT) {
console.log(`健康检查: 标签页 ${tabId} 错误次数超过${this.MAX_HEALTH_CHECK_ERROR_COUNT},停止刷新`);
this.stopRefresh(tabId);
}
} catch (error) {
console.log(`健康检查: 标签页 ${tabId} 不存在,停止刷新`);
this.stopRefresh(tabId);
}
}
// 清理过期的存储数据
await this.cleanupStorage();
} catch (error) {
console.error('健康检查时出错:', error);
}
}
async cleanupStorage() {
try {
const storage = await chrome.storage.local.get();
const keysToRemove = [];
// 清理过期的通知时间戳
const now = Date.now();
for (const [key, value] of Object.entries(storage)) {
if (key.startsWith('lastNotification_') && typeof value === 'number') {
if (now - value > this.NOTIFICATION_CLEANUP_AGE) {
keysToRemove.push(key);
}
}
}
if (keysToRemove.length > 0) {
await chrome.storage.local.remove(keysToRemove);
console.log(`清理了 ${keysToRemove.length} 个过期存储项`);
}
} catch (error) {
console.error('清理存储时出错:', error);
}
}
handleSuspend() {
console.log('扩展即将暂停,保存状态');
this.isShuttingDown = true;
// 立即保存所有待保存的状态
if (this.saveTimers) {
for (const [tabId, timerId] of this.saveTimers.entries()) {
clearTimeout(timerId);
const refresher = this.activeRefreshers.get(tabId);
if (refresher) {
this.saveRefresherState(tabId, refresher, true);
}
}
this.saveTimers.clear();
}
// 清理定时器
if (this.healthCheckInterval) {
clearInterval(this.healthCheckInterval);
}
// 暂停所有刷新器,但保留状态
for (const [tabId, timerId] of this.timers.entries()) {
clearTimeout(timerId);
}
this.timers.clear();
}
handleStartup() {
console.log('扩展启动,恢复状态');
this.isShuttingDown = false;
this.restoreState();
this.startHealthCheck();
// 更新图标状态
this.updateIconOnExtensionStart();
}
detectEdge() {
try {
// 检测Edge特征
const userAgent = navigator.userAgent;
const isEdge = userAgent.includes('Edg/') || userAgent.includes('Edge/');
// 检测Edge特有的API
const hasEdgeFeatures = typeof chrome.runtime.getContexts !== 'undefined' ||
chrome.runtime.getURL('').includes('-extension://');
console.log('🔍 浏览器检测:', { userAgent, isEdge, hasEdgeFeatures });
return isEdge || hasEdgeFeatures;
} catch (error) {
console.error('💥 浏览器检测失败:', error);
return false;
}
}
initEdgeCompatibility() {
console.log('🔧 初始化Edge兼容性设置...');
// Edge的定时器可能不太稳定,增加缓冲时间
this.edgeTimerBuffer = 1000; // 1秒缓冲
// Edge可能需要更多的权限检查
this.needsExtraPermissionChecks = true;
// Edge的通知API可能不同
this.edgeNotificationFallback = true;
}
async performRefreshEdgeCompatible(tabId) {
console.log(`🔄 Edge兼容模式刷新 - TabId: ${tabId}`);
try {
// Edge特定的权限检查
if (this.needsExtraPermissionChecks) {
const permissions = await chrome.permissions.contains({
permissions: ['tabs'],
origins: ['<all_urls>']
});
if (!permissions) {
console.log('⚠️ Edge权限不足,尝试请求权限');
// 在Edge中不能直接请求权限,需要用户手动授权
throw new Error('Edge权限不足,请重新安装扩展');
}
}
// 使用更稳定的标签页获取方法
const tab = await this.getTabForEdge(tabId);
if (!tab || !this.isValidTab(tab)) {
throw new Error('标签页无效或不存在');
}
// Edge中使用更安全的刷新方法
await chrome.tabs.reload(tabId, { bypassCache: false });
console.log(`✅ Edge兼容模式刷新成功 - TabId: ${tabId}`);
return true;
} catch (error) {
console.error(`💥 Edge兼容模式刷新失败 - TabId: ${tabId}:`, error);
return false;
}
}
async getTabForEdge(tabId) {
// Edge使用相同的重试逻辑,但可能需要更多次数
try {
return await this.getTabWithRetry(tabId, this.isEdge ? 3 : 2);
} catch (error) {
console.error('💥 Edge标签页获取失败:', error);
return null;
}
}
async showNotificationEdgeCompatible(tabId, refreshCount) {
if (!this.edgeNotificationFallback) {
return this.showNotification(tabId, refreshCount);
}
try {
// Edge中使用更简单的通知方式
const tab = await this.getTabForEdge(tabId);
const title = tab?.title || '未知页面';
// 检查通知权限
const permission = await chrome.permissions.contains({ permissions: ['notifications'] });
if (!permission) {
console.log('⚠️ Edge通知权限不足');
return;
}
chrome.notifications.create(`refresh_${tabId}_${Date.now()}`, {
type: 'basic',
iconUrl: 'icons/icon48.png',
title: '页面已刷新',
message: `${title}\n刷新次数: ${refreshCount}`
});
} catch (error) {
console.error('💥 Edge通知显示失败:', error);
}
}
// 图标管理相关方法
initIconManagement() {
// 监听标签页激活事件
chrome.tabs.onActivated.addListener((activeInfo) => {
this.updateIconForTab(activeInfo.tabId).catch(err => {
console.log('标签页激活时更新图标失败:', err.message);
});
});
// 监听标签页更新事件
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete') {
this.updateIconForTab(tabId).catch(err => {
console.log('标签页更新时更新图标失败:', err.message);
});
}
});
// 设置默认图标状态
this.setDefaultIcon();
}
async updateIconForTab(tabId) {
try {
// 先检查标签页是否存在
const tab = await chrome.tabs.get(tabId);
if (!tab) {
console.log(`⚠️ 标签页 ${tabId} 不存在,跳过图标更新`);
return;
}
const isSupported = this.isValidTab(tab);
const isRunning = this.activeRefreshers.has(tabId);
if (isSupported) {
await this.setNormalIcon();
this.iconState.set(tabId, 'normal');
// 如果正在运行,显示运行状态badge
if (isRunning) {
await this.setRunningBadge();
} else {
await this.clearBadge();
}
} else {
await this.setGrayIcon();
this.iconState.set(tabId, 'gray');
}
console.log(`🎨 图标状态更新 - TabId: ${tabId}, 支持: ${isSupported ? '是' : '否'}, 运行中: ${isRunning ? '是' : '否'}, URL: ${tab.url}`);
} catch (error) {
// 标签页可能已关闭,这是正常情况
if (error.message && error.message.includes('No tab with id')) {
console.log(`ℹ️ 标签页 ${tabId} 已关闭,跳过图标更新`);
// 清理该标签页的状态
this.iconState.delete(tabId);
return;
}
console.error('更新图标状态失败:', error);
// 其他错误时尝试设置为灰色图标
try {
await this.setGrayIcon();
} catch (iconError) {
console.error('设置灰色图标也失败:', iconError);
}
}
}
async setNormalIcon() {
try {
await chrome.action.setIcon({
path: {
16: 'icons/icon16.png',
32: 'icons/icon32.png',
48: 'icons/icon48.png',
128: 'icons/icon128.png'
}
});
// 注意:不在这里清除badge,由调用者决定
} catch (error) {
console.error('设置正常图标失败:', error);
}
}
async setGrayIcon() {
try {
await chrome.action.setIcon({
path: {
16: 'icons/icon16_gray.png',
32: 'icons/icon32_gray.png',
48: 'icons/icon48_gray.png',
128: 'icons/icon128_gray.png'
}
});
await this.clearBadge();
} catch (error) {
console.error('设置灰色图标失败,使用badge替代:', error);
// 如果灰色图标不存在,尝试设置badge
try {
await chrome.action.setBadgeText({ text: '×' });
await chrome.action.setBadgeBackgroundColor({ color: '#888888' });
} catch (badgeError) {
console.error('设置badge失败:', badgeError);
}
}
}
async setDefaultIcon() {
// 获取当前活动标签页并更新图标
try {
const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (activeTab && activeTab.id) {
await this.updateIconForTab(activeTab.id);
} else {
await this.setNormalIcon();
await this.clearBadge();
}
} catch (error) {
console.error('设置默认图标失败:', error);
try {
await this.setNormalIcon();
await this.clearBadge();
} catch (iconError) {
console.error('设置正常图标失败:', iconError);
}
}
}
// 扩展启动/激活时更新图标状态
async updateIconOnExtensionStart() {
try {
const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (activeTab && activeTab.id) {
await this.updateIconForTab(activeTab.id);
} else {
console.log('扩展启动时无活动标签页,使用默认图标');
await this.setDefaultIcon();
}
} catch (error) {
console.error('扩展启动时更新图标失败:', error);
// 失败时使用默认图标
await this.setDefaultIcon().catch(err => {
console.error('设置默认图标也失败:', err);
});
}
}
// 扩展错误时设置为灰色图标
async setErrorIcon() {
await this.setGrayIcon();
try {
await chrome.action.setBadgeText({ text: '!' });
await chrome.action.setBadgeBackgroundColor({ color: '#ff4444' });
} catch (error) {
console.error('设置错误badge失败:', error);
}
}
// 设置运行状态badge
async setRunningBadge() {
try {
await chrome.action.setBadgeText({ text: '●' });
await chrome.action.setBadgeBackgroundColor({ color: '#4CAF50' }); // 绿色表示运行中
} catch (error) {
console.error('设置运行badge失败:', error);
}
}
// 清除badge
async clearBadge() {
try {
await chrome.action.setBadgeText({ text: '' });
} catch (error) {
console.error('清除badge失败:', error);
}
}
}
// 初始化服务
new RefreshService();