-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathgemini_chat_export.user.js
More file actions
1999 lines (1780 loc) · 72 KB
/
Copy pathgemini_chat_export.user.js
File metadata and controls
1999 lines (1780 loc) · 72 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
// ==UserScript==
// @name Gemini 聊天对话增强脚本
// @namespace http://tampermonkey.net/
// @version 1.2.0
// @description 一键导出 Google Gemini 的网页端对话聊天记录为 JSON / TXT / Markdown 文件,支持对话内目录导航。
// @author sxuan
// @match https://gemini.google.com/app*
// @match https://gemini.google.com/u/*/app*
// @grant GM_addStyle
// @grant GM_setClipboard
// @icon data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCACAyNCIgZmlsbD0iIzAwNzhmZiI+PHBhdGggZD0iTTE5LjUgMi4yNWgtMTVjLTEuMjQgMC0yLjI1IDEuMDEtMi4yNSAyLjI1djE1YzAgMS4yNCAxLjAxIDIuMjUgMi4yNSAyLjI1aDE1YzEuMjQgMCAyLjI1LTEuMDEgMi4yNS0yLjI1di0xNWMwLTEuMjQtMS4wMS0yLjI1LTIuMjUtMi4yNXptLTIuMjUgNmgtMTAuNWMtLjQxIDAtLjc1LS4zNC0uNzUtLjc1cy4zNC0uNzUuNzUtLjc1aDEwLjVjLjQxIDAgLjc1LjM0Ljc1Ljc1cy0uMzQuNzUtLjc1Ljc1em0wIDRoLTEwLjVjLS40MSAwLS43NS0uMzQtLjc1LS43NXMuMzQtLjc1Ljc1LS43NWgxMC41Yy40MSAwIC43NS4zNC43NS43NXMtLjM0Ljc1LS4yNS43NXptLTMgNGgtNy41Yy0uNDEgMC0uNzUtLjM0LS43NS0uNzVzLjM0LS43NS43NS0uNzVoNy41Yy40MSAwIC43NS4zNC43NS43NXMtLjM0Ljc1LS43NS43NXoiLz48L3N2Zz4=
// @updateURL https://raw.githubusercontent.com/Sxuan-Coder/gemini_chat_export/main/gemini_chat_export.user.js
// @downloadURL https://raw.githubusercontent.com/Sxuan-Coder/gemini_chat_export/main/gemini_chat_export.user.js
// @license Apache-2.0
// ==/UserScript==
(function () {
'use strict';
// TrustedTypes 策略引用
let trustedHTMLPolicy = null;
if (window.trustedTypes && window.trustedTypes.createPolicy) {
try {
if (!window.trustedTypes.defaultPolicy) {
trustedHTMLPolicy = window.trustedTypes.createPolicy('default', {
createHTML: (string) => string,
createScript: (string) => string,
createScriptURL: (string) => string
});
} else {
trustedHTMLPolicy = window.trustedTypes.defaultPolicy;
}
} catch (e) {
try {
trustedHTMLPolicy = window.trustedTypes.createPolicy('gemini-export-policy', {
createHTML: (string) => string,
createScript: (string) => string,
createScriptURL: (string) => string
});
} catch (e2) {
console.warn('TrustedTypes 策略创建失败,使用 DOM API 替代', e2);
}
}
}
const safeSetInnerHTML = (element, html) => {
if (!element) return;
if (trustedHTMLPolicy) {
try {
element.innerHTML = trustedHTMLPolicy.createHTML(html);
return;
} catch (e) { }
}
if (window.trustedTypes && window.trustedTypes.defaultPolicy) {
try {
element.innerHTML = window.trustedTypes.defaultPolicy.createHTML(html);
return;
} catch (e) { }
}
if (!window.trustedTypes) {
element.innerHTML = html;
return;
}
try {
const template = document.createElement('template');
if (element.setHTML) {
element.setHTML(html);
return;
}
while (element.firstChild) {
element.removeChild(element.firstChild);
}
const range = document.createRange();
range.selectNode(document.body);
const fragment = range.createContextualFragment(html);
element.appendChild(fragment);
} catch (e) {
console.warn('safeSetInnerHTML 回退到纯文本', e);
element.textContent = html.replace(/<[^>]*>/g, '');
}
};
// --- 全局配置常量 ---
window.__GEMINI_EXPORT_FORMAT = window.__GEMINI_EXPORT_FORMAT || 'txt';
const buttonTextStartScroll = "滚动导出对话";
const buttonTextStopScroll = "停止滚动";
const buttonTextProcessingScroll = "处理滚动数据...";
const successTextScroll = "滚动导出对话成功!";
const errorTextScroll = "滚动导出失败";
const buttonTextCanvasExport = "导出Canvas";
const buttonTextCanvasProcessing = "处理Canvas数据...";
const successTextCanvas = "Canvas 导出成功!";
const errorTextCanvas = "Canvas 导出失败";
const buttonTextCombinedExport = "一键导出对话+Canvas";
const buttonTextCombinedProcessing = "处理组合数据...";
const successTextCombined = "组合导出成功!";
const errorTextCombined = "组合导出失败";
const exportTimeout = 3000;
const SCROLL_DELAY_MS = 1000;
const MAX_SCROLL_ATTEMPTS = 300;
const SCROLL_INCREMENT_FACTOR = 0.85;
const SCROLL_STABILITY_CHECKS = 3;
if (!window.__GEMINI_EXPORT_FORMAT) { window.__GEMINI_EXPORT_FORMAT = 'txt'; }
// --- 脚本内部状态变量 ---
let isScrolling = false;
let collectedData = new Map();
let scrollCount = 0;
let noChangeCounter = 0;
let captureButtonScroll = null;
let stopButtonScroll = null;
let captureButtonCanvas = null;
let captureButtonCombined = null;
let statusDiv = null;
let hideButton = null;
let buttonContainer = null;
let sidePanel = null;
let toggleButton = null;
let formatSelector = null;
let conversationDirectoryPanel = null;
let conversationDirectoryContainer = null;
let conversationDirectoryObserver = null;
let conversationDirectoryUpdateTimer = null;
let conversationDirectoryAnchorSeq = 0;
let conversationDirectoryLastSignature = '';
let directoryCollapsed = false;
let directoryDragState = { isDragging: false, startX: 0, startY: 0, startTop: 0, startRight: 0 };
const DIRECTORY_POS_KEY = 'gemini_export_directory_position';
const DIRECTORY_COLLAPSED_KEY = 'gemini_export_directory_collapsed';
let themeObserver = null;
let themeUpdateTimer = null;
let currentThemeMode = null;
let toastContainer = null;
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function parseRgbColor(colorString) {
if (!colorString) return null;
const m = colorString.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i);
if (!m) return null;
return { r: Number(m[1]), g: Number(m[2]), b: Number(m[3]) };
}
function getPageBackgroundColor() {
try {
const bodyBg = window.getComputedStyle(document.body).backgroundColor;
if (bodyBg && bodyBg !== 'rgba(0, 0, 0, 0)' && bodyBg !== 'transparent') return bodyBg;
} catch (_) { }
try {
return window.getComputedStyle(document.documentElement).backgroundColor;
} catch (_) { }
return '';
}
function detectPageThemeMode() {
try {
const scheme = window.getComputedStyle(document.documentElement).colorScheme;
if (scheme && scheme.includes('dark')) return 'dark';
if (scheme && scheme.includes('light')) return 'light';
} catch (_) { }
const rgb = parseRgbColor(getPageBackgroundColor());
if (rgb) {
const luminance = (0.2126 * rgb.r) + (0.7152 * rgb.g) + (0.0722 * rgb.b);
return luminance < 128 ? 'dark' : 'light';
}
try {
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
} catch (_) { }
return 'dark';
}
function applyThemeVariables(mode) {
const darkVars = {
'--ge-panel-bg': 'rgba(30, 30, 45, 0.85)',
'--ge-panel-text': '#F9FAFB',
'--ge-text-muted': '#D1D5DB',
'--ge-text-muted-2': '#9CA3AF',
'--ge-border': 'rgba(255, 255, 255, 0.15)',
'--ge-border-hover': 'rgba(255, 255, 255, 0.35)',
'--ge-surface': 'rgba(255, 255, 255, 0.08)',
'--ge-surface-2': 'rgba(30, 30, 45, 0.95)',
'--ge-surface-hover': 'rgba(255, 255, 255, 0.12)',
'--ge-divider': 'rgba(255, 255, 255, 0.08)',
'--ge-primary': '#3b82f6',
'--ge-primary-hover': '#60a5fa',
'--ge-primary-border': '#3b82f6',
'--ge-on-primary': '#FFFFFF',
'--ge-success': '#10b981',
'--ge-success-border': '#10b981',
'--ge-danger': '#ef4444',
'--ge-danger-border': '#ef4444',
'--ge-neutral': '#64748b',
'--ge-neutral-border': '#64748b',
'--ge-scroll-thumb': 'rgba(255, 255, 255, 0.2)',
'--ge-scroll-thumb-hover': 'rgba(255, 255, 255, 0.35)',
'--ge-accent': '#f59e0b',
'--ge-gradient-primary': 'linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%)',
'--ge-gradient-success': 'linear-gradient(135deg, #11998e 0%, #10b981 100%)',
'--ge-gradient-danger': 'linear-gradient(135deg, #ed213a 0%, #ef4444 100%)',
'--ge-glass-blur': 'blur(20px) saturate(180%)',
'--ge-glass-shadow': '0 12px 48px rgba(31, 38, 135, 0.25)',
'--ge-font-family': "'Outfit', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif"
};
const lightVars = {
'--ge-panel-bg': 'rgba(255, 255, 255, 0.75)',
'--ge-panel-text': '#1F2937',
'--ge-text-muted': '#4B5563',
'--ge-text-muted-2': '#6B7280',
'--ge-border': 'rgba(255, 255, 255, 0.9)',
'--ge-border-hover': 'rgba(255, 255, 255, 0.6)',
'--ge-surface': 'rgba(255, 255, 255, 0.5)',
'--ge-surface-2': 'rgba(255, 255, 255, 0.9)',
'--ge-surface-hover': 'rgba(255, 255, 255, 0.65)',
'--ge-divider': 'rgba(255, 255, 255, 0.7)',
'--ge-primary': '#3b82f6',
'--ge-primary-hover': '#2563eb',
'--ge-primary-border': '#3b82f6',
'--ge-on-primary': '#FFFFFF',
'--ge-success': '#10b981',
'--ge-success-border': '#10b981',
'--ge-danger': '#ef4444',
'--ge-danger-border': '#ef4444',
'--ge-neutral': '#64748b',
'--ge-neutral-border': '#64748b',
'--ge-scroll-thumb': 'rgba(0, 0, 0, 0.15)',
'--ge-scroll-thumb-hover': 'rgba(0, 0, 0, 0.3)',
'--ge-accent': '#f59e0b',
'--ge-gradient-primary': 'linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%)',
'--ge-gradient-success': 'linear-gradient(135deg, #11998e 0%, #10b981 100%)',
'--ge-gradient-danger': 'linear-gradient(135deg, #ed213a 0%, #ef4444 100%)',
'--ge-glass-blur': 'blur(20px) saturate(180%)',
'--ge-glass-shadow': '0 12px 48px rgba(31, 38, 135, 0.15)',
'--ge-font-family': "'Outfit', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif"
};
const vars = mode === 'light' ? lightVars : darkVars;
Object.entries(vars).forEach(([key, value]) => {
document.documentElement.style.setProperty(key, value);
});
currentThemeMode = mode;
}
function refreshThemeIfNeeded() {
const nextMode = detectPageThemeMode();
if (nextMode === currentThemeMode) return;
applyThemeVariables(nextMode);
}
function scheduleThemeRefresh(delayMs = 120) {
if (themeUpdateTimer) window.clearTimeout(themeUpdateTimer);
themeUpdateTimer = window.setTimeout(() => {
themeUpdateTimer = null;
refreshThemeIfNeeded();
}, delayMs);
}
function startThemeSync() {
applyThemeVariables(detectPageThemeMode());
if (themeObserver) themeObserver.disconnect();
themeObserver = new MutationObserver(() => scheduleThemeRefresh(120));
try {
themeObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ['class', 'style', 'data-theme', 'data-color-scheme', 'color-scheme']
});
} catch (_) { }
try {
themeObserver.observe(document.body, {
attributes: true,
attributeFilter: ['class', 'style']
});
} catch (_) { }
try {
const media = window.matchMedia('(prefers-color-scheme: dark)');
if (media && media.addEventListener) media.addEventListener('change', () => scheduleThemeRefresh(120));
else if (media && media.addListener) media.addListener(() => scheduleThemeRefresh(120));
} catch (_) { }
}
function getCurrentTimestamp() {
const n = new Date();
const YYYY = n.getFullYear();
const MM = (n.getMonth() + 1).toString().padStart(2, '0');
const DD = n.getDate().toString().padStart(2, '0');
const hh = n.getHours().toString().padStart(2, '0');
const mm = n.getMinutes().toString().padStart(2, '0');
const ss = n.getSeconds().toString().padStart(2, '0');
return `${YYYY}${MM}${DD}_${hh}${mm}${ss}`;
}
function getProjectName() {
try {
const firstUser = document.querySelector('#chat-history user-query .query-text, #chat-history user-query .query-text-line, #chat-history user-query .query-text p');
if (firstUser && firstUser.textContent && firstUser.textContent.trim()) {
const raw = firstUser.textContent.trim().replace(/\s+/g, ' ');
const clean = raw.substring(0, 20).replace(/[\\/:\*\?"<>\|]/g, '_');
if (clean) return `Gemini_${clean}`;
}
} catch (e) { console.warn('Gemini 项目名提取失败,回退 XPath', e); }
const xpath = "/html/body/app-root/ms-app/div/div/div/div/span/ms-prompt-switcher/ms-chunk-editor/section/ms-toolbar/div/div[1]/div/div/h1";
const defaultName = "GeminiChat";
try {
const result = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
const titleElement = result.singleNodeValue;
if (titleElement && titleElement.textContent) {
const cleanName = titleElement.textContent.trim().replace(/[\\/:\*\?"<>\|]/g, '_');
return cleanName || defaultName;
}
} catch (e) { }
return defaultName;
}
function getMainScrollerElement_AiStudio() {
console.log("尝试查找滚动容器 (用于滚动导出)...");
let scroller = document.querySelector('.chat-scrollable-container');
if (scroller && scroller.scrollHeight > scroller.clientHeight) {
console.log("找到滚动容器 (策略 1: .chat-scrollable-container):", scroller);
return scroller;
}
scroller = document.querySelector('mat-sidenav-content');
if (scroller && scroller.scrollHeight > scroller.clientHeight) {
console.log("找到滚动容器 (策略 2: mat-sidenav-content):", scroller);
return scroller;
}
const chatTurnsContainer = document.querySelector('ms-chat-turn')?.parentElement;
if (chatTurnsContainer) {
let parent = chatTurnsContainer;
for (let i = 0; i < 5 && parent; i++) {
if (parent.scrollHeight > parent.clientHeight + 10 &&
(window.getComputedStyle(parent).overflowY === 'auto' || window.getComputedStyle(parent).overflowY === 'scroll')) {
console.log("找到滚动容器 (策略 3: 向上查找父元素):", parent);
return parent;
}
parent = parent.parentElement;
}
}
console.warn("警告 (滚动导出): 未能通过特定选择器精确找到 AI Studio 滚动区域,将尝试使用 document.documentElement。如果滚动不工作,请按F12检查聊天区域的HTML结构,并更新此函数内的选择器。");
return document.documentElement;
}
// Gemini 新增滚动容器获取与解析逻辑
function getMainScrollerElement_Gemini() {
return document.querySelector('#chat-history') || document.documentElement;
}
function extractDataIncremental_Gemini() {
let newly = 0, updated = false;
const nodes = document.querySelectorAll('#chat-history .conversation-container');
const seenUserTexts = new Set(); // 用于去重用户消息
nodes.forEach((c, idx) => {
let info = collectedData.get(c) || { domOrder: idx, type: 'unknown', userText: null, thoughtText: null, responseText: null };
let changed = false;
if (!collectedData.has(c)) { collectedData.set(c, info); newly++; }
if (!info.userText) {
const userTexts = Array.from(c.querySelectorAll('user-query .query-text-line, user-query .query-text p, user-query .query-text'))
.map(el => el.innerText.trim()).filter(Boolean);
if (userTexts.length) {
const combinedUserText = userTexts.join('\n');
// 检查是否已经存在相同的用户消息
if (!seenUserTexts.has(combinedUserText)) {
seenUserTexts.add(combinedUserText);
info.userText = combinedUserText;
changed = true;
if (info.type === 'unknown') info.type = 'user';
}
}
}
const modelRoot = c.querySelector('.response-container-content, model-response');
if (modelRoot) {
if (!info.responseText) {
const md = modelRoot.querySelector('.model-response-text .markdown');
if (md && md.innerText.trim()) { info.responseText = md.innerText.trim(); changed = true; }
}
if (!info.thoughtText) {
const thoughts = modelRoot.querySelector('model-thoughts');
if (thoughts) {
let textReal = '';
const body = thoughts.querySelector('.thoughts-body, .thoughts-content');
if (body && body.innerText.trim() && !/显示思路/.test(body.innerText.trim())) textReal = body.innerText.trim();
info.thoughtText = textReal || '(思维链未展开)'; // 占位策略 A
changed = true;
}
}
}
if (changed) {
if (info.userText && info.responseText && info.thoughtText) info.type = 'model_thought_reply';
else if (info.userText && info.responseText) info.type = 'model_reply';
else if (info.userText) info.type = 'user';
else if (info.responseText && info.thoughtText) info.type = 'model_thought_reply';
else if (info.responseText) info.type = 'model_reply';
else if (info.thoughtText) info.type = 'model_thought';
collectedData.set(c, info); updated = true;
}
});
updateStatus(`滚动 ${scrollCount}/${MAX_SCROLL_ATTEMPTS}... 已收集 ${collectedData.size} 条记录..`);
scheduleConversationDirectoryUpdate(0);
return newly > 0 || updated;
}
function extractDataIncremental_Dispatch() {
if (document.querySelector('#chat-history .conversation-container')) return extractDataIncremental_Gemini();
return extractDataIncremental_AiStudio();
}
function scheduleConversationDirectoryUpdate(delayMs = 200) {
if (!conversationDirectoryContainer) return;
if (conversationDirectoryUpdateTimer) window.clearTimeout(conversationDirectoryUpdateTimer);
conversationDirectoryUpdateTimer = window.setTimeout(() => {
conversationDirectoryUpdateTimer = null;
updateConversationDirectory();
}, delayMs);
}
function ensureConversationAnchor(element) {
if (!element) return null;
const existing = element.dataset.geminiExportAnchorId;
if (existing) return existing;
if (element.id) {
element.dataset.geminiExportAnchorId = element.id;
return element.id;
}
conversationDirectoryAnchorSeq += 1;
const id = `gemini-export-anchor-${conversationDirectoryAnchorSeq}`;
element.id = id;
element.dataset.geminiExportAnchorId = id;
return id;
}
function collectUserPromptsForDirectory() {
const results = [];
const geminiContainers = document.querySelectorAll('#chat-history .conversation-container');
if (geminiContainers && geminiContainers.length) {
const seenTexts = new Set();
geminiContainers.forEach((c) => {
// 优先尝试获取最具体的文本元素,避免重复
let userText = '';
const queryTextLine = c.querySelector('user-query .query-text-line');
const queryTextP = c.querySelector('user-query .query-text p');
const queryText = c.querySelector('user-query .query-text');
if (queryTextLine) {
userText = (queryTextLine.innerText || '').trim();
} else if (queryTextP) {
userText = (queryTextP.innerText || '').trim();
} else if (queryText) {
userText = (queryText.innerText || '').trim();
}
if (!userText) return;
// 去重:避免相同文本多次出现
if (seenTexts.has(userText)) return;
seenTexts.add(userText);
const anchorId = ensureConversationAnchor(c);
if (!anchorId) return;
results.push({ anchorId, text: userText });
});
return results;
}
const turns = document.querySelectorAll('ms-chat-turn');
if (turns && turns.length) {
turns.forEach((turn) => {
const userContainer = turn.querySelector('.chat-turn-container.user');
if (!userContainer) return;
const userNode = turn.querySelector('.turn-content ms-cmark-node');
const text = (userNode ? userNode.innerText : turn.innerText) || '';
const cleaned = text.trim().replace(/\s+/g, ' ');
if (!cleaned) return;
const anchorId = ensureConversationAnchor(turn);
if (!anchorId) return;
results.push({ anchorId, text: cleaned });
});
}
return results;
}
function renderConversationDirectoryItems(items) {
safeSetInnerHTML(conversationDirectoryContainer, '');
if (!items.length) {
const empty = document.createElement('div');
empty.textContent = '未检测到用户提问';
empty.style.cssText = 'padding: 10px; color: var(--ge-text-muted-2); font-size: 12px;';
conversationDirectoryContainer.appendChild(empty);
return;
}
items.forEach((item, idx) => {
const row = document.createElement('div');
row.className = 'gemini-conversation-directory-item';
row.dataset.anchorId = item.anchorId;
const preview = item.text.replace(/\s+/g, ' ').trim();
const shortText = preview.length > 60 ? `${preview.slice(0, 60)}...` : preview;
row.textContent = `${idx + 1}. ${shortText}`;
conversationDirectoryContainer.appendChild(row);
});
}
function updateConversationDirectory() {
if (!conversationDirectoryContainer) return;
const items = collectUserPromptsForDirectory();
// 目录签名:包含文本片段,确保同一锚点内容补全时也能刷新
const signature = items.map(i => `${i.anchorId}:${i.text.slice(0, 80)}`).join('|');
if (signature === conversationDirectoryLastSignature) return;
conversationDirectoryLastSignature = signature;
renderConversationDirectoryItems(items);
}
function startConversationDirectoryObserver() {
if (conversationDirectoryObserver) conversationDirectoryObserver.disconnect();
const root = document.querySelector('#chat-history') || document.body;
conversationDirectoryObserver = new MutationObserver(() => {
scheduleConversationDirectoryUpdate(150);
});
conversationDirectoryObserver.observe(root, { childList: true, subtree: true });
}
// 目录面板位置持久化
function loadDirectoryPosition() {
try {
const saved = localStorage.getItem(DIRECTORY_POS_KEY);
if (saved) return JSON.parse(saved);
} catch (_) { }
return null;
}
function saveDirectoryPosition(top, right) {
try {
localStorage.setItem(DIRECTORY_POS_KEY, JSON.stringify({ top, right }));
} catch (_) { }
}
function loadDirectoryCollapsed() {
try {
return localStorage.getItem(DIRECTORY_COLLAPSED_KEY) === 'true';
} catch (_) { }
return false;
}
function saveDirectoryCollapsed(collapsed) {
try {
localStorage.setItem(DIRECTORY_COLLAPSED_KEY, collapsed ? 'true' : 'false');
} catch (_) { }
}
// 目录面板折叠切换
function toggleDirectoryCollapse() {
if (!conversationDirectoryPanel || !conversationDirectoryContainer) return;
directoryCollapsed = !directoryCollapsed;
conversationDirectoryContainer.style.display = directoryCollapsed ? 'none' : 'block';
const toggleBtn = conversationDirectoryPanel.querySelector('.directory-toggle-btn');
if (toggleBtn) toggleBtn.textContent = directoryCollapsed ? '+' : '-';
saveDirectoryCollapsed(directoryCollapsed);
}
// 目录面板拖拽
function initDirectoryDrag() {
if (!conversationDirectoryPanel) return;
const header = conversationDirectoryPanel.querySelector('.directory-header');
if (!header) return;
header.style.cursor = 'move';
header.addEventListener('mousedown', (e) => {
// 点击折叠按钮时不启动拖拽
if (e.target.classList.contains('directory-toggle-btn')) return;
e.preventDefault();
const rect = conversationDirectoryPanel.getBoundingClientRect();
directoryDragState = {
isDragging: true,
startX: e.clientX,
startY: e.clientY,
startTop: rect.top,
startRight: window.innerWidth - rect.right
};
conversationDirectoryPanel.style.transition = 'none';
});
document.addEventListener('mousemove', (e) => {
if (!directoryDragState.isDragging) return;
const deltaX = e.clientX - directoryDragState.startX;
const deltaY = e.clientY - directoryDragState.startY;
let newTop = directoryDragState.startTop + deltaY;
let newRight = directoryDragState.startRight - deltaX;
// 边界限制
newTop = Math.max(10, Math.min(window.innerHeight - 100, newTop));
newRight = Math.max(10, Math.min(window.innerWidth - 100, newRight));
conversationDirectoryPanel.style.top = newTop + 'px';
conversationDirectoryPanel.style.right = newRight + 'px';
});
document.addEventListener('mouseup', () => {
if (!directoryDragState.isDragging) return;
directoryDragState.isDragging = false;
conversationDirectoryPanel.style.transition = '';
// 保存位置
const top = parseInt(conversationDirectoryPanel.style.top, 10);
const right = parseInt(conversationDirectoryPanel.style.right, 10);
saveDirectoryPosition(top, right);
});
}
// --- UI 界面创建与更新 ---
function createUI() {
console.log("开始创建 UI 元素...");
// 创建右侧折叠按钮
toggleButton = document.createElement('div');
toggleButton.id = 'gemini-export-toggle';
safeSetInnerHTML(toggleButton, '<');
toggleButton.style.cssText = `
position: fixed;
top: 50%;
right: 0;
width: 40px;
height: 60px;
background: var(--ge-gradient-primary);
color: var(--ge-on-primary);
border: 1px solid rgba(255, 255, 255, 0.3);
border-right: none;
border-radius: 16px 0 0 16px;
cursor: pointer;
z-index: 10001;
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
font-weight: bold;
box-shadow: var(--ge-glass-shadow);
backdrop-filter: var(--ge-glass-blur);
-webkit-backdrop-filter: var(--ge-glass-blur);
transition: all 200ms cubic-bezier(0.4, 0, 0.2, 1);
transform: translateY(-50%);
`;
document.body.appendChild(toggleButton);
// 创建右侧面板
sidePanel = document.createElement('div');
sidePanel.id = 'gemini-export-panel';
sidePanel.style.cssText = `
position: fixed;
top: 0;
right: -420px;
width: 400px;
height: 100vh;
background: var(--ge-panel-bg);
backdrop-filter: var(--ge-glass-blur);
-webkit-backdrop-filter: var(--ge-glass-blur);
border-left: 1px solid var(--ge-border);
z-index: 10000;
transition: right 200ms cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: var(--ge-glass-shadow);
overflow-y: auto;
font-family: var(--ge-font-family);
`;
document.body.appendChild(sidePanel);
// 创建对话目录面板(独立于折叠侧栏,支持折叠和拖拽)
conversationDirectoryPanel = document.createElement('div');
conversationDirectoryPanel.id = 'gemini-conversation-directory-panel';
// 加载保存的位置
const savedPos = loadDirectoryPosition();
const initTop = savedPos?.top ?? 90;
const initRight = savedPos?.right ?? 44;
conversationDirectoryPanel.style.cssText = `
position: fixed;
top: ${initTop}px;
right: ${initRight}px;
width: 280px;
max-height: 400px;
background: var(--ge-panel-bg);
backdrop-filter: var(--ge-glass-blur);
-webkit-backdrop-filter: var(--ge-glass-blur);
border: 1px solid var(--ge-border);
border-radius: 12px;
z-index: 9999;
overflow: hidden;
font-family: var(--ge-font-family);
transition: right 200ms cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: var(--ge-glass-shadow);
`;
// 加载折叠状态
directoryCollapsed = loadDirectoryCollapsed();
safeSetInnerHTML(conversationDirectoryPanel, `
<div class="directory-header" style="padding: 10px 12px; border-bottom: 1px solid var(--ge-border); color: var(--ge-panel-text); font-size: 13px; font-weight: 600; display: flex; justify-content: space-between; align-items: center; user-select: none;">
<span>对话目录</span>
<button class="directory-toggle-btn" style="width: 24px; height: 24px; border: none; background: var(--ge-surface); color: var(--ge-panel-text); border-radius: 4px; cursor: pointer; font-size: 14px; font-weight: bold; line-height: 1;">${directoryCollapsed ? '+' : '-'}</button>
</div>
<div id="conversation-directory" style="max-height: 340px; overflow: auto; display: ${directoryCollapsed ? 'none' : 'block'};"></div>
`);
document.body.appendChild(conversationDirectoryPanel);
// 绑定折叠按钮事件
const toggleBtn = conversationDirectoryPanel.querySelector('.directory-toggle-btn');
if (toggleBtn) {
toggleBtn.addEventListener('click', (e) => {
e.stopPropagation();
toggleDirectoryCollapse();
});
}
// 面板内容
safeSetInnerHTML(sidePanel, `
<div style="padding: 24px 20px; color: var(--ge-panel-text); font-family: var(--ge-font-family);">
<div style="display: flex; align-items: center; margin-bottom: 20px;">
<div style="width: 4px; height: 20px; background: var(--ge-accent); margin-right: 10px; border-radius: 2px;"></div>
<h2 style="margin: 0; font-size: 18px; font-weight: 600;">Gemini 导出助手</h2>
</div>
<p style="margin: 0 0 20px 0; font-size: 13px; color: var(--ge-text-muted); line-height: 1.5;">一键导出聊天记录与 Canvas 内容</p>
<div style="background: var(--ge-surface); border: 1px solid var(--ge-border); border-radius: 12px; padding: 14px; margin-bottom: 20px; backdrop-filter: blur(10px);">
<h3 style="margin: 0 0 10px 0; font-size: 13px; color: var(--ge-panel-text); font-weight: 600;">使用提示</h3>
<div style="font-size: 12px; color: var(--ge-text-muted); line-height: 1.6;">
<div style="margin-bottom: 6px;">导出前建议先滚动到对话顶部,避免缺失</div>
<div>如页面结构更新导致无法识别,请更新选择器</div>
</div>
</div>
<div style="margin-bottom: 20px;">
<h3 style="margin: 0 0 12px 0; font-size: 13px; color: var(--ge-panel-text); font-weight: 600;">导出格式</h3>
<div id="format-selector" style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px;">
<div class="format-option aihub-format-btn" data-format="txt" style="padding: 12px 8px; background: var(--ge-surface); border-radius: 12px; text-align: center; cursor: pointer; font-size: 12px; border: 1px solid var(--ge-border); position: relative; transition: all 200ms cubic-bezier(0.4, 0, 0.2, 1);">
<div style="font-weight: 600; margin-bottom: 2px;">TXT</div>
<div style="color: var(--ge-text-muted-2); font-size: 10px;">纯文本</div>
</div>
<div class="format-option aihub-format-btn" data-format="json" style="padding: 12px 8px; background: var(--ge-surface); border-radius: 12px; text-align: center; cursor: pointer; font-size: 12px; border: 1px solid var(--ge-border); position: relative; transition: all 200ms cubic-bezier(0.4, 0, 0.2, 1);">
<div style="font-weight: 600; margin-bottom: 2px;">JSON</div>
<div style="color: var(--ge-text-muted-2); font-size: 10px;">结构化</div>
</div>
<div class="format-option aihub-format-btn" data-format="md" style="padding: 12px 8px; background: var(--ge-surface); border-radius: 12px; text-align: center; cursor: pointer; font-size: 12px; border: 1px solid var(--ge-border); position: relative; transition: all 200ms cubic-bezier(0.4, 0, 0.2, 1);">
<div style="font-weight: 600; margin-bottom: 2px;">MD</div>
<div style="color: var(--ge-text-muted-2); font-size: 10px;">Markdown</div>
</div>
</div>
</div>
<!-- 功能按钮区域 -->
<div id="button-container" style="display: flex; flex-direction: column; gap: 12px;">
<!-- 滚动导出按钮 -->
<button id="capture-chat-scroll-button" class="aihub-button aihub-button-primary" style="
width: 100%;
padding: 14px;
background: var(--ge-gradient-primary);
color: var(--ge-on-primary);
border: none;
border-radius: 99px;
cursor: pointer;
font-size: 14px;
font-weight: 600;
font-family: var(--ge-font-family);
transition: all 200ms cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.35);
">${buttonTextStartScroll}</button>
<!-- Canvas导出按钮 -->
<button id="capture-canvas-button" class="aihub-button aihub-button-success" style="
width: 100%;
padding: 14px;
background: var(--ge-gradient-success);
color: var(--ge-on-primary);
border: none;
border-radius: 99px;
cursor: pointer;
font-size: 14px;
font-weight: 600;
font-family: var(--ge-font-family);
transition: all 200ms cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: 0 4px 15px rgba(16, 185, 129, 0.35);
">${buttonTextCanvasExport}</button>
<!-- 组合导出按钮 -->
<button id="capture-combined-button" class="aihub-button aihub-button-neutral" style="
width: 100%;
padding: 14px;
background: var(--ge-surface);
color: var(--ge-panel-text);
border: 1px solid var(--ge-border);
border-radius: 99px;
cursor: pointer;
font-size: 14px;
font-weight: 600;
font-family: var(--ge-font-family);
transition: all 200ms cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
">${buttonTextCombinedExport}</button>
<!-- 停止按钮 -->
<button id="stop-scrolling-button" class="aihub-button aihub-button-danger" style="
width: 100%;
padding: 14px;
background: var(--ge-gradient-danger);
color: var(--ge-on-primary);
border: none;
border-radius: 99px;
cursor: pointer;
font-size: 14px;
font-weight: 600;
font-family: var(--ge-font-family);
transition: all 200ms cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: 0 4px 15px rgba(239, 68, 68, 0.35);
display: none;
">${buttonTextStopScroll}</button>
</div>
<!-- 状态信息 -->
<div id="extract-status-div" class="aihub-status" style="
margin-top: 20px;
padding: 12px 14px;
background: var(--ge-surface);
border: 1px solid var(--ge-border);
border-radius: 12px;
font-size: 12px;
line-height: 1.5;
display: none;
color: var(--ge-text-muted);
backdrop-filter: blur(10px);
"></div>
<!-- 进度条 -->
<div id="export-progress-container" style="margin-top: 16px; display: none;">
<div class="aihub-progress-bar" style="height: 6px; background: var(--ge-surface); border-radius: 3px; overflow: hidden;">
<div id="export-progress-fill" style="height: 100%; width: 0%; background: var(--ge-gradient-primary); border-radius: 3px; transition: width 200ms ease;"></div>
</div>
</div>
<!-- Toast 容器 -->
<div id="aihub-toast-container" style="position: fixed; top: 20px; right: 20px; z-index: 10010; display: flex; flex-direction: column; gap: 10px;"></div>
<!-- 版权信息 -->
<div style="margin-top: 28px; padding-top: 20px; border-top: 1px solid var(--ge-divider); text-align: center; font-size: 11px; color: var(--ge-text-muted-2);">
<div style="margin-bottom: 6px;">v1.2.0 | sxuan © 2025-2026</div>
<a href="https://github.com/Sxuan-Coder/gemini_chat_export" target="_blank" style="color: var(--ge-primary); text-decoration: none; font-size: 11px;">GitHub</a>
</div>
</div>
`);
// 获取元素引用
captureButtonScroll = document.getElementById('capture-chat-scroll-button');
captureButtonCanvas = document.getElementById('capture-canvas-button');
captureButtonCombined = document.getElementById('capture-combined-button');
stopButtonScroll = document.getElementById('stop-scrolling-button');
statusDiv = document.getElementById('extract-status-div');
formatSelector = document.getElementById('format-selector');
conversationDirectoryContainer = document.getElementById('conversation-directory');
// 初始化格式选择器
initFormatSelector();
// 添加事件监听器
captureButtonScroll.addEventListener('click', handleScrollExtraction);
captureButtonCanvas.addEventListener('click', handleCanvasExtraction);
captureButtonCombined.addEventListener('click', handleCombinedExtraction);
stopButtonScroll.addEventListener('click', () => {
if (isScrolling) {
updateStatus('手动停止滚动信号已发送..');
isScrolling = false;
stopButtonScroll.disabled = true;
stopButtonScroll.textContent = '正在停止...';
}
});
// 折叠按钮点击事件
toggleButton.addEventListener('click', togglePanel);
conversationDirectoryContainer.addEventListener('click', (event) => {
const target = event.target.closest('.gemini-conversation-directory-item');
if (!target) return;
const anchorId = target.dataset.anchorId;
if (!anchorId) return;
const anchorEl = document.getElementById(anchorId);
if (!anchorEl) return;
anchorEl.scrollIntoView({ behavior: 'smooth', block: 'start' });
target.classList.add('active');
window.setTimeout(() => target.classList.remove('active'), 1200);
});
// 添加样式
GM_addStyle(`
/* 胶囊按钮悬停效果 */
.aihub-button:hover {
transform: translateY(-2px);
filter: brightness(1.08);
}
.aihub-button:active {
transform: translateY(0);
filter: brightness(0.95);
}
.aihub-button:disabled {
opacity: 0.6;
cursor: not-allowed;
transform: none !important;
filter: grayscale(0.5) !important;
}
/* 主按钮 */
.aihub-button-primary:hover {
box-shadow: 0 6px 20px rgba(102, 126, 234, 0.5) !important;
}
/* 成功按钮 */
.aihub-button-success:hover {
box-shadow: 0 6px 20px rgba(16, 185, 129, 0.5) !important;
}
/* 危险按钮 */
.aihub-button-danger:hover {
box-shadow: 0 6px 20px rgba(239, 68, 68, 0.5) !important;
}
/* 成功/错误状态 */
.success {
background: var(--ge-gradient-success) !important;
box-shadow: 0 4px 15px rgba(16, 185, 129, 0.4) !important;
}
.error {
background: var(--ge-gradient-danger) !important;
box-shadow: 0 4px 15px rgba(239, 68, 68, 0.4) !important;
}
/* 格式选项悬停 */
.format-option:hover {
border-color: var(--ge-border-hover) !important;
background: var(--ge-surface-hover) !important;
}
.format-option.selected {
border-color: var(--ge-primary) !important;
background: rgba(59, 130, 246, 0.15) !important;
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
}
/* 触发器悬停 */
#gemini-export-toggle:hover {
right: 8px;
transform: translateY(-50%) scale(1.05);
box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
}
/* 面板滚动条 */
#gemini-export-panel::-webkit-scrollbar {
width: 6px;
}
#gemini-export-panel::-webkit-scrollbar-track {
background: transparent;
}
#gemini-export-panel::-webkit-scrollbar-thumb {
background: var(--ge-scroll-thumb);
border-radius: 3px;
}
#gemini-export-panel::-webkit-scrollbar-thumb:hover {
background: var(--ge-scroll-thumb-hover);
}
/* 目录滚动条 */
#conversation-directory::-webkit-scrollbar {
width: 5px;
}
#conversation-directory::-webkit-scrollbar-track {
background: transparent;
}
#conversation-directory::-webkit-scrollbar-thumb {
background: var(--ge-scroll-thumb);
border-radius: 3px;
}
#conversation-directory::-webkit-scrollbar-thumb:hover {
background: var(--ge-scroll-thumb-hover);
}
/* 目录项 */
.gemini-conversation-directory-item {
padding: 10px 12px;
font-size: 12px;
line-height: 1.4;
color: var(--ge-panel-text);
border-bottom: 1px solid var(--ge-divider);
cursor: pointer;
transition: all 150ms ease;
}
.gemini-conversation-directory-item:hover {
background: var(--ge-surface-hover);
padding-left: 16px;
}
.gemini-conversation-directory-item.active {