-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js.bak
More file actions
2254 lines (1953 loc) · 90 KB
/
script.js.bak
File metadata and controls
2254 lines (1953 loc) · 90 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
// 搜索引擎图标
const searchEngineIcons = {
google: 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"%3E%3Cpath fill="%234285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/%3E%3Cpath fill="%2334A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/%3E%3Cpath fill="%23FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/%3E%3Cpath fill="%23EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/%3E%3C/svg%3E',
bing: 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"%3E%3Crect fill="%2300A4EF" x="1" y="1" width="10" height="10"/%3E%3Crect fill="%237FBA00" x="13" y="1" width="10" height="10"/%3E%3Crect fill="%23FFB900" x="1" y="13" width="10" height="10"/%3E%3Crect fill="%23F25022" x="13" y="13" width="10" height="10"/%3E%3C/svg%3E',
baidu: 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"%3E%3Ccircle cx="12" cy="12" r="11" fill="%23FF6B2B"/%3E%3Cpath fill="white" d="M12 2c5.5 0 10 4.5 10 10s-4.5 10-10 10S2 17.5 2 12 6.5 2 12 2M8 10c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm8 0c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm-4 8c2.2 0 4-1.8 4-4h-8c0 2.2 1.8 4 4 4z"/%3E%3C/svg%3E'
};
// 获取网站 favicon
function getFaviconUrl(urlString) {
try {
const url = new URL(urlString);
const hostname = url.hostname;
// 返回多个favicon源的数组,按优先级排列
return [
`https://www.google.com/s2/favicons?domain=${hostname}&sz=64`,
`https://icons.duckduckgo.com/ip3/${hostname}.ico`,
`${url.protocol}//${hostname}/favicon.ico`
];
} catch (e) {
return [];
}
}
// 搜索引擎和搜索类型配置
const searchEngines = {
google: {
web: 'https://www.google.com/search?q={query}',
images: 'https://www.google.com/search?q={query}&tbm=isch',
news: 'https://news.google.com/search?q={query}',
video: 'https://www.google.com/search?q={query}&tbm=vid',
maps: 'https://www.google.com/maps/search/{query}'
},
bing: {
web: 'https://www.bing.com/search?q={query}',
images: 'https://www.bing.com/images/search?q={query}',
news: 'https://www.bing.com/news/search?q={query}',
video: 'https://www.bing.com/videos/search?q={query}',
maps: 'https://www.bing.com/maps?q={query}'
},
baidu: {
web: 'https://www.baidu.com/s?wd={query}',
images: 'https://image.baidu.com/search/index?tn=baiduimage&word={query}',
news: 'https://news.baidu.com/news?wd={query}',
video: 'https://v.baidu.com/v?ct=301&s=25&ie=utf-8&word={query}',
maps: 'https://api.map.baidu.com/place/search?query={query}'
}
};
// 默认快捷方式
const defaultApps = [
{ name: "Bilibili", url: "https://www.bilibili.com", color: "#fb7299", text: "B", iconType: "color" },
{ name: "GitHub", url: "https://github.com", color: "#24292e", text: "G", iconType: "color" },
{ name: "Stack Overflow", url: "https://stackoverflow.com", color: "#f48024", text: "SO", iconType: "color" },
{ name: "MDN", url: "https://developer.mozilla.org", color: "#000", text: "MDN", iconType: "color" },
];
// 默认设置
const defaultSettings = {
wallpaperSource: 'local',
maskOpacity: 45,
wallpaperBlur: 0,
gridCols: 6,
showIconLabel: false,
iconShadow: true,
iconAnimation: true,
iconRadius: 50,
iconOpacity: 100,
iconSize: 90,
hideSearchBar: false,
searchWidth: 60,
searchHeight: 44,
searchRadius: 50,
searchOpacity: 95,
searchTopMargin: 0,
textShadow: true,
textSize: 14,
textColor: '#ffffff',
currentSearchEngine: 'google'
};
// 全局变量
const pageSize = 12;
let currentPage = 0;
let allApps = [];
let settings = { ...defaultSettings };
let currentSearchType = 'web';
// 编辑模式
let isEditMode = false;
let editingItemIndex = null;
let draggedItem = null;
let draggedIndex = null;
// DOM 元素
const body = document.getElementById('body');
const grid = document.getElementById('grid');
const sidebar = document.getElementById('sidebar');
const searchInput = document.getElementById('search-input');
const searchEngineSelector = document.querySelector('.search-engine-selector');
const searchEngineDropdownMenu = document.getElementById('search-engine-dropdown-menu');
const searchTypes = document.querySelectorAll('.search-type-btn');
const searchBox = document.querySelector('.search-box');
const searchEngineIcon = document.getElementById('search-engine-icon');
let currentSearchEngine = 'google';
const sidebarToggleBtn = document.getElementById('sidebar-toggle-btn');
const sidebarCloseBtn = document.getElementById('sidebar-close-btn');
const shortcutForm = document.getElementById('shortcut-form');
const iconTypeRadios = document.querySelectorAll('input[name="icon-type"]');
const wallpaperRefreshBtn = document.getElementById('wallpaper-refresh-btn');
const addTab = document.getElementById('add-tab');
const settingsTab = document.getElementById('settings-tab');
const addPanel = document.getElementById('add-panel');
const settingsPanel = document.getElementById('settings-panel');
// ==================== 壁纸辅助函数 ====================
function getWallpaperUrl(storageResult) {
// 根据设置的壁纸源返回存储中的壁纸URL
console.log('[getWallpaperUrl] Checking source:', settings.wallpaperSource, {
hasLocalData: !!storageResult.wallpaperData,
hasBingData: !!storageResult.currentBingWallpaper,
hasGoogleData: !!storageResult.currentGoogleWallpaper
});
if (settings.wallpaperSource === 'local' && storageResult.wallpaperData) {
console.log('[getWallpaperUrl] ✓ Returning local wallpaper');
return storageResult.wallpaperData;
}
if (settings.wallpaperSource === 'bing' && storageResult.currentBingWallpaper) {
console.log('[getWallpaperUrl] ✓ Returning Bing wallpaper');
return storageResult.currentBingWallpaper;
}
if (settings.wallpaperSource === 'google' && storageResult.currentGoogleWallpaper) {
console.log('[getWallpaperUrl] ✓ Returning Google wallpaper');
return storageResult.currentGoogleWallpaper;
}
console.warn('[getWallpaperUrl] No wallpaper found for source:', settings.wallpaperSource);
return null;
}
// 图片压缩函数:将图片压缩到安全大小以适应 chrome.storage.local 的 10MB 限制
function compressImage(dataUrl, maxSize = 8 * 1024 * 1024) {
return new Promise((resolve) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
let width = img.width;
let height = img.height;
let quality = 0.85;
let result = null;
// 设置初始 canvas 大小和绘制图片
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0);
result = canvas.toDataURL('image/jpeg', quality);
console.log(`[Compress] Initial size: ${(result.length / 1024 / 1024).toFixed(2)}MB`);
// 如果仍然过大,逐步降低质量或缩小尺寸
while (result.length > maxSize && quality > 0.3) {
quality -= 0.1;
result = canvas.toDataURL('image/jpeg', quality);
console.log(`[Compress] After quality ${quality.toFixed(2)}: ${(result.length / 1024 / 1024).toFixed(2)}MB`);
}
// 如果仍然过大,缩小尺寸
while (result.length > maxSize && width > 800) {
width = Math.floor(width * 0.8);
height = Math.floor(height * 0.8);
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
result = canvas.toDataURL('image/jpeg', quality);
console.log(`[Compress] After resize to ${width}x${height}: ${(result.length / 1024 / 1024).toFixed(2)}MB`);
}
const originalSize = (dataUrl.length / 1024 / 1024).toFixed(2);
const compressedSize = (result.length / 1024 / 1024).toFixed(2);
console.log(`[Compress] ✓ Image compressed: ${originalSize}MB → ${compressedSize}MB (${Math.round(compressedSize / originalSize * 100)}%)`);
resolve(result);
};
img.onerror = () => {
console.error('[Compress] Failed to load image for compression');
resolve(dataUrl);
};
img.src = dataUrl;
});
}
// 检测图像是否有透明背景(用于初始化时保存图标属性)
function checkImageTransparency(imageUrl) {
try {
const img = new Image();
img.crossOrigin = 'Anonymous';
return new Promise((resolve) => {
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imageData.data;
// 检查是否有透明像素(alpha < 255)
let hasTransparency = false;
for (let i = 3; i < data.length; i += 4) {
if (data[i] < 200) { // alpha 小于 200 视为透明
hasTransparency = true;
break;
}
}
resolve(hasTransparency);
};
img.onerror = () => {
// 如果加载失败,假设没有透明背景
resolve(false);
};
img.src = imageUrl;
});
} catch (e) {
// 如果出错,假设没有透明背景
return Promise.resolve(false);
}
}
// 将图像转换为 data URL 缓存
function convertImageToDataUrl(imageUrl) {
return new Promise((resolve) => {
const img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = () => {
try {
const canvas = document.createElement('canvas');
const width = img.naturalWidth || img.width;
const height = img.naturalHeight || img.height;
if (!width || !height) {
console.warn('[convertImageToDataUrl] Invalid image dimensions:', { width, height });
resolve(imageUrl); // 转换失败,返回原 URL
return;
}
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
const dataUrl = canvas.toDataURL('image/png');
console.log('[convertImageToDataUrl] ✓ Converted to data URL, size:', (dataUrl.length / 1024).toFixed(2) + 'KB');
resolve(dataUrl);
} catch (e) {
console.error('[convertImageToDataUrl] Conversion error:', e);
resolve(imageUrl); // 转换失败,返回原 URL
}
};
img.onerror = () => {
console.warn('[convertImageToDataUrl] Failed to load image:', imageUrl);
resolve(imageUrl); // 加载失败,返回原 URL
};
img.onabort = () => {
console.warn('[convertImageToDataUrl] Image loading aborted:', imageUrl);
resolve(imageUrl);
};
// 设置 5 秒超时
const timeout = setTimeout(() => {
console.warn('[convertImageToDataUrl] Image loading timeout:', imageUrl);
img.src = '';
resolve(imageUrl);
}, 5000);
// 成功加载后清除超时
const originalOnload = img.onload;
img.onload = function() {
clearTimeout(timeout);
originalOnload.call(this);
};
img.src = imageUrl;
});
}
// 初始化
document.addEventListener('DOMContentLoaded', () => {
setupSearch();
setupSidebar();
setupModal();
setupSettingsModal();
loadData();
});
// ==================== 数据存储 ====================
function loadData() {
chrome.storage.local.get(['apps', 'settings', 'wallpaperData', 'currentBingWallpaper', 'currentGoogleWallpaper', 'customSearchEngines', 'customEngineIcons'], (result) => {
// 恢复自定义搜索引擎
if (result.customSearchEngines) {
Object.assign(searchEngines, result.customSearchEngines);
}
if (result.customEngineIcons) {
Object.assign(searchEngineIconsData, result.customEngineIcons);
}
// 加载数据
if (result.apps && result.apps.length > 0) {
allApps = result.apps;
// 数据迁移:为旧应用添加 iconType 属性
let needSave = false;
allApps.forEach(app => {
if (!app.iconType) {
app.iconType = app.img ? 'upload' : 'color';
needSave = true;
}
});
if (needSave) {
saveAppsToStorage();
}
} else {
allApps = JSON.parse(JSON.stringify(defaultApps));
saveAppsToStorage();
}
if (result.settings) {
settings = { ...defaultSettings, ...result.settings };
} else {
settings = { ...defaultSettings };
saveSettingsToStorage();
}
// 恢复搜索引擎选择
if (settings.currentSearchEngine) {
currentSearchEngine = settings.currentSearchEngine;
updateSearchEngineIcon();
}
// 立即设置所有样式 - 包括遮罩、网格、搜索框等
// 重要:在任何渲染之前完成所有样式设置
body.style.setProperty('--mask-opacity', settings.maskOpacity / 100);
body.style.setProperty('--wallpaper-blur', settings.wallpaperBlur || 0);
body.style.setProperty('--search-width', settings.searchWidth + '%');
body.style.setProperty('--search-height', (settings.searchHeight || 44) + 'px');
body.style.setProperty('--search-radius', (settings.searchRadius || 50) + 'px');
body.style.setProperty('--search-opacity', settings.searchOpacity / 100);
// 应用其他设置(但不设置遮罩,避免重复)
applySettingsExceptMask();
initializeGridPresets();
setupSettingsModalUIValues();
// 立即加载壁纸
const wallpaperUrl = getWallpaperUrl(result);
console.log('[Wallpaper] wallpaperUrl:', wallpaperUrl ? wallpaperUrl.substring(0, 50) : 'null');
console.log('[Wallpaper] settings.wallpaperSource:', settings.wallpaperSource);
console.log('[Wallpaper] result.wallpaperData:', result.wallpaperData ? 'exists' : 'null');
console.log('[Wallpaper] result.currentBingWallpaper:', result.currentBingWallpaper ? 'exists' : 'null');
console.log('[Wallpaper] result.currentGoogleWallpaper:', result.currentGoogleWallpaper ? 'exists' : 'null');
if (wallpaperUrl) {
// 设置壁纸到 body::before 伪元素
const style = document.createElement('style');
style.textContent = `body::before { background-image: url("${wallpaperUrl}") !important; }`;
document.head.appendChild(style);
body.classList.add('has-wallpaper');
console.log('[Wallpaper] Set backgroundImage on body::before');
} else {
body.classList.remove('has-wallpaper');
console.log('[Wallpaper] No wallpaper in storage, will load async');
// 如果没有壁纸,异步加载网络壁纸
loadWallpaper();
}
// 所有准备就绪后,显示容器并渲染
document.querySelector('.container').classList.add('ready');
// 恢复自定义搜索引擎的下拉菜单项
const divider = document.querySelector('.dropdown-divider');
const defaultEngines = ['google', 'bing', 'baidu'];
Object.keys(searchEngines).forEach(engineKey => {
// 跳过内置引擎,只处理自定义的
if (defaultEngines.includes(engineKey)) return;
// 检查该选项是否已存在
if (document.querySelector(`[data-engine="${engineKey}"]`)) return;
const engineName = Object.keys(searchEngines).find(k =>
k === engineKey ? searchEngines[k] : false
);
// 获取引擎的第一个字母作为图标文字
const engineDisplayName = engineKey.charAt(0).toUpperCase() + engineKey.slice(1);
// 创建选项
const option = document.createElement('div');
option.className = 'dropdown-option';
option.dataset.engine = engineKey;
option.innerHTML = `
<svg class="dropdown-icon" viewBox="0 0 24 24">
<text x="12" y="16" text-anchor="middle" font-size="14" font-family="Arial" fill="#999">${engineDisplayName[0].toUpperCase()}</text>
</svg>
<span>${engineDisplayName}</span>
<button class="delete-engine-btn" title="Delete">×</button>
`;
// 插入到分隔线前
divider.parentNode.insertBefore(option, divider);
// 添加点击事件
option.addEventListener('click', (e) => {
if (e.target.classList.contains('delete-engine-btn')) return;
e.stopPropagation();
currentSearchEngine = engineKey;
settings.currentSearchEngine = engineKey;
document.querySelectorAll('.dropdown-option').forEach(opt => opt.classList.remove('active'));
option.classList.add('active');
updateSearchEngineIcon();
searchEngineSelector.classList.remove('active');
searchEngineDropdownMenu.classList.remove('show');
saveSettingsToStorage();
searchInput.focus();
});
// 添加删除按钮事件
const deleteBtn = option.querySelector('.delete-engine-btn');
deleteBtn.addEventListener('click', (e) => {
e.stopPropagation();
if (confirm(`确定删除"${engineDisplayName}"吗?`)) {
delete searchEngines[engineKey];
delete searchEngineIconsData[engineKey];
option.remove();
chrome.storage.local.set({
customSearchEngines: searchEngines,
customEngineIcons: searchEngineIconsData
});
if (currentSearchEngine === engineKey) {
currentSearchEngine = 'google';
settings.currentSearchEngine = 'google';
document.querySelectorAll('.dropdown-option').forEach(opt => opt.classList.remove('active'));
document.querySelector('[data-engine="google"]').classList.add('active');
updateSearchEngineIcon();
saveSettingsToStorage();
}
}
});
});
// 设置搜索引擎的 active 状态
document.querySelectorAll('.dropdown-option').forEach(option => {
if (option.dataset.engine === currentSearchEngine) {
option.classList.add('active');
} else {
option.classList.remove('active');
}
});
// 确保图标也与保存值同步
updateSearchEngineIcon();
render();
});
}
function initializeGridPresets() {
document.querySelectorAll('.grid-preset').forEach(btn => {
btn.classList.remove('active');
if (btn.dataset.cols === 'custom') {
// Custom button active if gridCols not in preset values
const presetValues = [3, 4, 5, 6, 8, 10];
if (!presetValues.includes(settings.gridCols)) {
btn.classList.add('active');
document.getElementById('custom-cols-item').classList.remove('hidden');
document.getElementById('custom-cols').value = settings.gridCols;
} else {
document.getElementById('custom-cols-item').classList.add('hidden');
}
} else {
const cols = parseInt(btn.dataset.cols);
if (cols === settings.gridCols) {
btn.classList.add('active');
document.getElementById('custom-cols-item').classList.add('hidden');
}
}
});
}
function saveAppsToStorage() {
chrome.storage.local.set({ apps: allApps });
}
function saveSettingsToStorage() {
chrome.storage.local.set({ settings });
// 只更新需要动态变化的样式
applySettings();
}
// ==================== 侧边栏功能 ====================
function setupSidebar() {
sidebarToggleBtn.addEventListener('click', () => {
sidebar.classList.add('open');
});
sidebarCloseBtn.addEventListener('click', () => {
sidebar.classList.remove('open');
});
// 标签页切换
addTab.addEventListener('click', () => {
switchTab('add');
});
settingsTab.addEventListener('click', () => {
switchTab('settings');
});
}
function switchTab(tabName) {
// 更新标签
document.querySelectorAll('.sidebar-tab').forEach(tab => {
tab.classList.remove('active');
});
document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');
// 更新面板
document.querySelectorAll('.tab-panel').forEach(panel => {
panel.classList.remove('active');
});
document.getElementById(`${tabName}-panel`).classList.add('active');
}
// ==================== 壁纸功能 ====================
// 统一的壁纸显示函数
function displayWallpaper(imageUrl, saveKey = null) {
// 设置壁纸到 body::before 伪元素
const style = document.createElement('style');
style.textContent = `body::before { background-image: url("${imageUrl}") !important; }`;
document.head.appendChild(style);
body.classList.add('has-wallpaper');
if (saveKey) {
const saveObj = {};
saveObj[saveKey] = imageUrl;
chrome.storage.local.set(saveObj);
}
console.log('[Wallpaper] Wallpaper displayed, saved key:', saveKey);
}
function loadWallpaper() {
console.log('[Wallpaper] Loading wallpaper source:', settings.wallpaperSource);
if (settings.wallpaperSource === 'local') {
// 本地壁纸:获取最新上传的壁纸
console.log('[Wallpaper] Loading local wallpaper...');
chrome.storage.local.get(['wallpaperData'], (result) => {
if (result.wallpaperData) {
displayWallpaper(result.wallpaperData, 'wallpaperData');
console.log('[Wallpaper] Local wallpaper loaded and saved');
} else {
console.log('[Wallpaper] No local wallpaper found');
}
});
wallpaperRefreshBtn.classList.remove('show');
} else if (settings.wallpaperSource === 'bing') {
// Bing壁纸:显示刷新按钮并自动加载
console.log('[Wallpaper] Bing wallpaper mode - showing refresh button and loading');
wallpaperRefreshBtn.classList.add('show');
// 自动加载一张Bing壁纸
fetchBingWallpaper();
} else if (settings.wallpaperSource === 'google') {
// Google壁纸:显示刷新按钮并自动加载
console.log('[Wallpaper] Google wallpaper mode - showing refresh button and loading');
wallpaperRefreshBtn.classList.add('show');
// 自动加载一张Google壁纸
fetchGoogleWallpaper();
}
}
function fetchBingWallpaper() {
console.log('[Wallpaper - Bing] Bing API has CORS restrictions, using fallback wallpapers');
const bingFallbackWallpapers = [
'https://www.bing.com/th?id=OHR.MerlionPark_EN-US1969991689_1920x1080.jpg',
'https://www.bing.com/th?id=OHR.ThailandLights_EN-US2050851255_1920x1080.jpg',
'https://www.bing.com/th?id=OHR.IslandBay_EN-US1903389508_1920x1080.jpg',
'https://www.bing.com/th?id=OHR.SaltFlats_EN-US1845236533_1920x1080.jpg',
'https://www.bing.com/th?id=OHR.MooningPlanet_EN-US1751910315_1920x1080.jpg',
'https://www.bing.com/th?id=OHR.PeacockinBloom_EN-US1934253670_1920x1080.jpg',
'https://www.bing.com/th?id=OHR.PrairieWolves_EN-US1823879373_1920x1080.jpg'
];
const randomIdx = Math.floor(Math.random() * bingFallbackWallpapers.length);
const imageUrl = bingFallbackWallpapers[randomIdx];
console.log('[Wallpaper - Bing] Selected fallback image index:', randomIdx);
const img = new Image();
let loaded = false;
img.onload = () => {
if (!loaded) {
loaded = true;
console.log('[Wallpaper - Bing] Image loaded successfully');
displayWallpaper(imageUrl, 'currentBingWallpaper');
}
};
img.onerror = () => {
if (!loaded) {
loaded = true;
console.log('[Wallpaper - Bing] Fallback image failed to load, using stored wallpaper');
useFallbackWallpaper();
}
};
img.src = imageUrl;
// 设置超时3秒,如果还没加载就使用fallback
setTimeout(() => {
if (!loaded) {
loaded = true;
console.log('[Wallpaper - Bing] Image load timeout, using stored wallpaper');
useFallbackWallpaper();
}
}, 3000);
}
function fetchGoogleWallpaper() {
// 只使用景观图片,不包含人物
const wallpaperUrls = [
'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=1920&h=1080&fit=crop', // 山景
'https://images.unsplash.com/photo-1506784983066-a8165c7a090d?w=1920&h=1080&fit=crop', // 海景
'https://images.unsplash.com/photo-1506704720897-c6b0b8ef6dba?w=1920&h=1080&fit=crop', // 森林
'https://images.unsplash.com/photo-1506519773649-6e0ee9d4cc6e?w=1920&h=1080&fit=crop', // 峡谷
'https://images.unsplash.com/photo-1495567720989-cebdbdd97913?w=1920&h=1080&fit=crop', // 日落
'https://images.unsplash.com/photo-1441974231531-c6227db76b6e?w=1920&h=1080&fit=crop', // 云景
'https://images.unsplash.com/photo-1506780773649-6e0ee9d4cc6e?w=1920&h=1080&fit=crop', // 夜景
'https://images.unsplash.com/photo-1505142468610-359e7d316be0?w=1920&h=1080&fit=crop' // 海浪
];
const randomIndex = Math.floor(Math.random() * wallpaperUrls.length);
const imageUrl = wallpaperUrls[randomIndex];
console.log('[Wallpaper - Google] Total URLs available:', wallpaperUrls.length);
console.log('[Wallpaper - Google] Selected image index:', randomIndex);
// 检查图片是否可以加载
const img = new Image();
let loaded = false;
img.onload = () => {
if (!loaded) {
loaded = true;
console.log('[Wallpaper - Google] Image loaded successfully');
displayWallpaper(imageUrl, 'currentGoogleWallpaper');
}
};
img.onerror = () => {
if (!loaded) {
loaded = true;
console.log('[Wallpaper - Google] Image failed to load, trying next...');
// 尝试加载下一张
tryNextImage(wallpaperUrls, randomIndex + 1);
}
};
console.log('[Wallpaper - Google] Starting image load...');
img.src = imageUrl;
// 设置超时2秒,如果还没加载就尝试下一张
setTimeout(() => {
if (!loaded) {
loaded = true;
console.log('[Wallpaper - Google] Image load timeout, trying next...');
img.src = ''; // 停止加载
tryNextImage(wallpaperUrls, randomIndex + 1);
}
}, 2000);
}
function tryNextImage(urls, startIndex) {
if (startIndex >= urls.length) {
console.log('[Wallpaper - Google] All images failed, using fallback');
useFallbackWallpaper();
return;
}
const imageUrl = urls[startIndex];
const img = new Image();
let loaded = false;
img.onload = () => {
if (!loaded) {
loaded = true;
console.log('[Wallpaper - Google] Fallback image loaded successfully, index:', startIndex);
displayWallpaper(imageUrl, 'currentGoogleWallpaper');
}
};
img.onerror = () => {
if (!loaded) {
loaded = true;
tryNextImage(urls, startIndex + 1);
}
};
img.src = imageUrl;
setTimeout(() => {
if (!loaded) {
loaded = true;
img.src = '';
tryNextImage(urls, startIndex + 1);
}
}, 2000);
}
function useFallbackWallpaper() {
// 优先尝试使用最后成功加载的壁纸,否则使用纯色背景
chrome.storage.local.get(['lastBingWallpaper', 'lastGoogleWallpaper'], (result) => {
if (result.lastBingWallpaper) {
body.style.backgroundImage = `url("${result.lastBingWallpaper}")`;
body.style.backgroundSize = 'cover';
body.style.backgroundPosition = 'center';
body.style.backgroundAttachment = 'fixed';
body.style.backgroundRepeat = 'no-repeat';
body.classList.add('has-wallpaper');
} else if (result.lastGoogleWallpaper) {
body.style.backgroundImage = `url("${result.lastGoogleWallpaper}")`;
body.style.backgroundSize = 'cover';
body.style.backgroundPosition = 'center';
body.style.backgroundAttachment = 'fixed';
body.style.backgroundRepeat = 'no-repeat';
body.classList.add('has-wallpaper');
} else {
// 使用纯色背景或默认图片
body.style.backgroundImage = 'none';
body.classList.remove('has-wallpaper');
}
});
}
// ==================== 搜索功能 ====================
function setupSearch() {
// 搜索引擎图标
updateSearchEngineIcon();
// 下拉菜单切换
searchEngineSelector.addEventListener('click', (e) => {
e.stopPropagation();
searchEngineSelector.classList.toggle('active');
searchEngineDropdownMenu.classList.toggle('show');
});
// 搜索引擎选项点击
document.querySelectorAll('.dropdown-option').forEach(option => {
// 选择搜索引擎事件
option.addEventListener('click', (e) => {
if (e.target.classList.contains('delete-engine-btn')) return;
e.stopPropagation();
const engine = option.dataset.engine;
currentSearchEngine = engine;
settings.currentSearchEngine = engine;
// 更新active状态
document.querySelectorAll('.dropdown-option').forEach(opt => opt.classList.remove('active'));
option.classList.add('active');
updateSearchEngineIcon();
searchEngineSelector.classList.remove('active');
searchEngineDropdownMenu.classList.remove('show');
// 保存设置
saveSettingsToStorage();
searchInput.focus();
});
// 删除搜索引擎事件(仅对自定义引擎)
const deleteBtn = option.querySelector('.delete-engine-btn');
if (deleteBtn) {
deleteBtn.addEventListener('click', (e) => {
e.stopPropagation();
const engine = option.dataset.engine;
const engineName = option.querySelector('span').textContent;
// 检查是否是内置引擎(不能删除)
if (['google', 'bing', 'baidu'].includes(engine)) {
alert('内置搜索引擎不能删除');
return;
}
if (confirm(`确定删除"${engineName}"吗?`)) {
delete searchEngines[engine];
delete searchEngineIconsData[engine];
option.remove();
// 保存到 storage
chrome.storage.local.set({
customSearchEngines: searchEngines,
customEngineIcons: searchEngineIconsData
});
// 如果删除的是当前搜索引擎,切换到Google
if (currentSearchEngine === engine) {
currentSearchEngine = 'google';
settings.currentSearchEngine = 'google';
document.querySelectorAll('.dropdown-option').forEach(opt => opt.classList.remove('active'));
document.querySelector('[data-engine="google"]').classList.add('active');
updateSearchEngineIcon();
saveSettingsToStorage();
}
}
});
}
});
// 点击外部关闭菜单
document.addEventListener('click', (e) => {
if (!e.target.closest('.search-box-wrapper')) {
searchEngineSelector.classList.remove('active');
searchEngineDropdownMenu.classList.remove('show');
}
});
// 搜索类型选项卡
searchTypes.forEach(btn => {
btn.addEventListener('click', () => {
searchTypes.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
currentSearchType = btn.dataset.type;
});
});
searchInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
const engine = currentSearchEngine;
const searchType = currentSearchType;
const query = searchInput.value.trim();
if (query) {
let url = searchEngines[engine][searchType];
// 替换{query}占位符
url = url.replace('{query}', encodeURIComponent(query));
window.location.href = url;
}
}
});
wallpaperRefreshBtn.addEventListener('click', () => {
if (settings.wallpaperSource === 'bing') {
fetchBingWallpaper();
} else if (settings.wallpaperSource === 'google') {
fetchGoogleWallpaper();
}
});
// 添加搜索引擎功能
const dropdownAdd = document.querySelector('.dropdown-add');
if (dropdownAdd) {
dropdownAdd.addEventListener('click', () => {
const name = prompt('输入搜索引擎名称 (如: DuckDuckGo)');
if (!name) return;
const baseUrl = prompt('输入搜索引擎的基础URL\n例: https://duckduckgo.com/\n(不需要手动添加查询参数)');
if (!baseUrl) return;
// 自动处理URL格式
let url = baseUrl.trim();
// 检查URL是否以=或?结尾,如果没有则自动添加
if (!url.endsWith('=') && !url.endsWith('?')) {
if (url.includes('?')) {
// URL中有?,则在末尾添加&和参数名=
url += '&q=';
} else {
// URL中没有?,则添加?和参数名=
url += '?q=';
}
}
// 在URL末尾添加{query}占位符
url += '{query}';
// 添加到搜索引擎配置
const engineKey = name.toLowerCase().replace(/\s+/g, '');
searchEngines[engineKey] = {
web: url
};
// 为自定义搜索引擎添加图标数据
searchEngineIconsData[engineKey] = {
color: '#' + Math.floor(Math.random()*16777215).toString(16),
text: name[0].toUpperCase()
};
// 保存到 storage
chrome.storage.local.set({
customSearchEngines: searchEngines,
customEngineIcons: searchEngineIconsData
});
// 创建新选项
const newOption = document.createElement('div');
newOption.className = 'dropdown-option';
newOption.dataset.engine = engineKey;
newOption.innerHTML = `
<svg class="dropdown-icon" viewBox="0 0 24 24">
<text x="12" y="16" text-anchor="middle" font-size="14" font-family="Arial" fill="#999">${name[0].toUpperCase()}</text>
</svg>
<span>${name}</span>
<button class="delete-engine-btn" title="Delete">×</button>
`;
// 插入到分隔线之前
const divider = document.querySelector('.dropdown-divider');
divider.parentNode.insertBefore(newOption, divider);
// 为新选项添加删除按钮事件
const deleteBtn = newOption.querySelector('.delete-engine-btn');
deleteBtn.addEventListener('click', (e) => {
e.stopPropagation();
if (confirm(`确定删除"${name}"吗?`)) {
delete searchEngines[engineKey];
delete searchEngineIconsData[engineKey];
newOption.remove();
// 保存到 storage
chrome.storage.local.set({
customSearchEngines: searchEngines,
customEngineIcons: searchEngineIconsData
});
// 如果删除的是当前搜索引擎,切换到Google
if (currentSearchEngine === engineKey) {
currentSearchEngine = 'google';
settings.currentSearchEngine = 'google';
document.querySelectorAll('.dropdown-option').forEach(opt => opt.classList.remove('active'));
document.querySelector('[data-engine="google"]').classList.add('active');
updateSearchEngineIcon();
saveSettingsToStorage();
}
}
});
// 为新选项添加点击事件(选择搜索引擎)
newOption.addEventListener('click', (e) => {
if (e.target.classList.contains('delete-engine-btn')) return;
e.stopPropagation();
currentSearchEngine = engineKey;
settings.currentSearchEngine = engineKey;
// 更新active状态
document.querySelectorAll('.dropdown-option').forEach(opt => opt.classList.remove('active'));
newOption.classList.add('active');
updateSearchEngineIcon();
searchEngineSelector.classList.remove('active');
searchEngineDropdownMenu.classList.remove('show');
// 保存设置
saveSettingsToStorage();
searchInput.focus();
});
// 关闭菜单
searchEngineSelector.classList.remove('active');
searchEngineDropdownMenu.classList.remove('show');
});
}
}
// 搜索引擎SVG图标定义
const searchEngineIconsData = {
google: { color: '#4285F4', text: 'G' },
bing: { color: '#00A4EF', text: 'B' },
baidu: { color: '#FF6B2B', text: '百' }
};
function updateSearchEngineIcon() {
const engine = currentSearchEngine;
const iconData = searchEngineIconsData[engine];
if (iconData) {
const searchEngineIcon = document.getElementById('search-engine-icon');
searchEngineIcon.innerHTML = `
<svg class="icon-svg" viewBox="1 1 22 22" xmlns="http://www.w3.org/2000/svg" style="overflow: visible;">
<circle cx="12" cy="12" r="11" fill="${iconData.color}"/>
<text x="12" y="12" text-anchor="middle" dominant-baseline="central" font-size="16" font-weight="bold" font-family="Arial, sans-serif" fill="white">${iconData.text}</text>