-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent-script.js
More file actions
492 lines (462 loc) · 16.5 KB
/
content-script.js
File metadata and controls
492 lines (462 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
// content.js
// Injected on toolbar click. Exports current chat page to standalone HTML.
const TEMPLATE_HTML = `
<!DOCTYPE html>
<html lang="en-EN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{{title}}</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif; line-height: 1.6; max-width: 1200px; margin: 0 auto; padding: 20px; background-color: #f5f5f5; }
.chat-container { background: #fff; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,.1); overflow: hidden; }
.chat-header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: #fff; padding: 20px; text-align: center; }
.chat-header h1 { margin: 0; font-size: 1.5em; }
.chat-header .export-info { margin-top: 10px; font-size: .9em; opacity: .9; }
.message { padding: 20px; border-bottom: 1px solid #eee; }
.message:last-child { border-bottom: none; }
.message-header { font-weight: bold; margin-bottom: 10px; padding: 8px 12px; border-radius: 6px; display: inline-block; }
.message-header.user { background: #e3f2fd; color: #1976d2; }
.message-header.assistant { background: #f3e5f5; color: #7b1fa2; }
.message-header.system { background: #fff3e0; color: #f57c00; }
.message-header.unknown { background: #f5f5f5; color: #666; }
.message-content { margin-top: 10px; }
/* Header 1 Style */
h1 {
font-size: 1.5em;
margin: 1.2em 0 0.7em 0;
font-weight: 700;
line-height: 1.2;
}
h2 {
font-size: 1.2em;
margin: 1.1em 0 0.6em 0;
font-weight: 600;
line-height: 1.25;
}
/* Dialog message N title style */
.message-header {
font-size: 1.2em;
font-weight: 600;
margin-bottom: 10px;
padding: 8px 12px;
border-radius: 6px;
display: inline-block;
background: #f5f5f5;
color: #666;
}
/* Code block beautification(Darkboxstyle+title frame) */
.code-block-box {
margin: 1.5em 0;
border-radius: 10px;
box-shadow: 0 2px 8px rgba(0,0,0,0.08);
background: #181c24;
border: 1px solid #23272f;
overflow: hidden;
}
.code-title-frame {
display: flex;
align-items: center;
justify-content: space-between;
background: #f5f6fa;
color: #23272f;
font-size: 13px;
font-family: 'JetBrains Mono', 'Fira Mono', 'Consolas', 'Menlo', 'Monaco', 'monospace';
padding: 0.35em 1.1em 0.35em 1.1em;
border-bottom: 1px solid #e0e0e0;
border-radius: 10px 10px 0 0;
}
.code-lang-label {
font-weight: 600;
background: #23272f;
color: #e6eaf3;
opacity: 1;
letter-spacing: 0.5px;
border-radius: 5px;
padding: 0.15em 0.7em;
font-size: 90%;
margin-right: 0.5em;
display: inline-block;
}
.copy-button {
background: #e6eaf3;
color: #23272f;
border: none;
border-radius: 6px;
padding: 2px 12px;
font-size: 12px;
cursor: pointer;
opacity: 0.85;
transition: background 0.2s, opacity 0.2s;
z-index: 2;
}
.copy-button:hover {
background: #d3d7e3;
opacity: 1;
}
.code-block-box pre {
background: #181c24;
color: #e6eaf3;
border: none;
border-radius: 0 0 10px 10px;
margin: 0;
padding: 1em 1.2em;
font-size: 14px;
overflow-x: auto;
box-shadow: none;
}
.code-block-box code {
background: none;
color: inherit;
padding: 0;
border: none;
font-size: inherit;
}
code:not(pre code) {
background: #23272f;
color: #e6eaf3;
border-radius: 5px;
padding: 0.2em 0.4em;
font-size: 95%;
}
</style>
</head>
<body>
<div class="chat-container">
<div class="chat-header">
<h1>{{title}}</h1>
<div class="export-info">Export time: {{exportTime}} GMT+8 | Platform: {{platform}}</div>
</div>
{{content}}
</div>
</body>
</html>
`;
(function() {
function formatExportTime() {
const now = new Date();
return now.toLocaleString('en-US', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
}).replace(/(\d+)\/(\d+)\/(\d+),?\s*(\d+):(\d+):(\d+)/, '$3/$1/$2 at $4:$5:$6');
}
function detectPlatform() {
const url = (location.href || '').toLowerCase();
if (url.includes('chatgpt') || url.includes('openai')) return 'chatgpt';
if (url.includes('claude') || url.includes('anthropic')) return 'claude';
if (url.includes('deepseek')) return 'deepseek';
if (url.includes('cursor')) return 'cursor';
if (url.includes('copilot')) return 'copilot';
return 'unknown';
}
function getTitleFallback() {
let title = document.title || 'Chat';
const titleSelectors = [
'h1',
'.text-2xl',
'[data-testid="conversation-title"]',
'.conversation-title',
'.chat-title',
'title'
];
for (const s of titleSelectors) {
try {
const el = document.querySelector(s);
if (el && el.textContent && el.textContent.trim()) {
title = el.textContent.trim();
break;
}
} catch (_) {}
}
return title;
}
// Clean up labels <button> and <svg>
function cleanContent(content) {
if (!content) return '';
content = content.replace(/<button(\s[^>]*)?>([\s\S]*?)<\/button>/gi, '');
content = content.replace(/<svg[\s\S]*?<\/svg>/gi, '');
return content;
}
// Inline Claude chat parser
function parseClaudeMessages(doc) {
const messageBlocks = Array.from(doc.querySelectorAll('div.group'));
const messages = messageBlocks.map(block => {
// Extract contents regardless roles
const aiContent = block.querySelector('.font-claude-response');
if (aiContent) {
const html = aiContent.querySelector('.standard-markdown, .progressive-markdown');
let content = html ? html.innerHTML : aiContent.innerHTML;
content = cleanContent(content);
return { content };
}
const userContent = block.querySelector('[data-testid="user-message"]');
if (userContent) {
let content = userContent.innerHTML;
content = cleanContent(content);
return { content };
}
return null;
}).filter(Boolean);
return messages;
}
async function gatherMessages() {
const platform = detectPlatform();
if (platform === 'claude') {
try {
return parseClaudeMessages(document);
} catch (e) {
console.error('Claude parser failed:', e);
alert('Claude parser failed, chat not exported');
return [];
}
}
// All messages use 'Message N', regardless roles
const messages = [];
const messageSelectors = [
'[data-message-author-role]',
'[data-testid="conversation-turn"]',
'.conversation-turn',
'.message',
'.chat-message',
'.conversation-message',
'[class*="message"]',
'[class*="turn"]',
'[class*="conversation"]'
];
let messageElements = [];
for (const selector of messageSelectors) {
messageElements = document.querySelectorAll(selector);
if (messageElements.length > 0) {
break;
}
}
if (messageElements.length === 0) {
messageElements = document.querySelectorAll('div, section, article');
}
messageElements.forEach((element, index) => {
try {
let content = "";
const contentSelectors = [
'.markdown',
'[data-message-content]',
'.prose',
'.message-content',
'.conversation-content',
'.content',
'.text',
'.message-text'
];
let contentElement = null;
for (const selector of contentSelectors) {
contentElement = element.querySelector(selector);
if (contentElement) break;
}
if (!contentElement) {
contentElement = element;
}
if (contentElement) {
content = contentElement.innerHTML || contentElement.textContent || "";
content = cleanContent(content);
content = content
.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')
.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
.replace(/on\w+="[^"]*"/gi, '')
.trim();
}
if (content && content.length > 10) {
messages.push({ index, content });
}
} catch (e) {
// skip
}
});
return messages;
}
// Dynamically load templates and styles,Render export content
async function buildHTMLAsync({ title, exportTime, platform, messages }) {
// Used uniformly across all platforms template.html
function enhanceCodeBlocks(html) {
// step1:Give <pre> first after <div>language tag</div> Add style class
html = html.replace(
/<pre[^>]*>\s*<div[^>]*>([^<]+)<\/div>/i,
function(match, preAttrs, divAttrs, langText) {
const lang = langText.trim();
if (lang) {
// Check if there is already class property
if (/class\s*=\s*["']/.test(divAttrs)) {
const newDivAttrs = divAttrs.replace(
/class\s*=\s*["']([^"']*)["']/,
'class="$1 code-lang-label"'
);
return `<pre${preAttrs}><div${newDivAttrs}>${lang}</div>`;
} else {
return `<pre${preAttrs}><div${divAttrs} class="code-lang-label">${lang}</div>`;
}
}
return match;
}
);
// step2:Unified handling of all code block structures(Keep your original logic)
function wrapCodeBlockWithLang(line, codeBlockHtml, codeAttrs, codeContent) {
// Directly wrap code blocks,Language tags are no longer processed(Already in step1deal with)
return `<div class="code-block-box"><pre><code${codeAttrs}>${codeContent}</code></pre></div>`;
}
// deal with <code ...><span>...</span></code> structure
// matchChatGPTThe complete code block structure of
html = html.replace(
/<pre[^>]*>[\s\S]*?<div[^>]*class="[^"]*rounded-2xl[^"]*"[^>]*>[\s\S]*?<div[^>]*class="flex items-center[^"]*">([^<]+)<\/div>[\s\S]*?<code([^>]*)>\s*<span([^>]*)>([\s\S]*?)<\/span>\s*<\/code>[\s\S]*?<\/div>\s*<\/pre>/gi,
function(match, lang, codeAttrs, spanAttrs, codeContent) {
return `<div class="code-block-box">
<div class="code-lang-label">${lang.trim()}</div>
<pre><code${codeAttrs}><span${spanAttrs}>${codeContent}</span></code></pre>
</div>`;
}
);
//Claude
// Claudecode block capture(full version,Contains language tags)
html = html.replace(
/<div class="text-text-500 font-small[^"]*">([^<]+)<\/div>\s*<div>\s*<pre[^>]*class="code-block__code[^"]*"[^>]*>\s*<code([^>]*)>([\s\S]*?)<\/code>\s*<\/pre>\s*<\/div>/gi,
function(match, lang, codeAttrs, codeContent) {
return `<div class="code-block-box">
<div class="code-lang-label">${lang.trim()}</div>
<pre><code${codeAttrs}>${codeContent}</code></pre>
</div>`;
}
);
//Copilot
// Matches the entire code block container(Include language tags)
html = html.replace(
/<div class="rounded-xl[^"]*"[\s\S]*?<span class="capitalize">([^<]+)<\/span>[\s\S]*?<pre[^>]*>\s*<code([^>]*)>\s*<span([^>]*)>([\s\S]*?)<\/span>\s*<\/code>\s*<\/pre>[\s\S]*?<\/div>/gi,
function(match, lang, codeAttrs, spanAttrs, codeContent) {
return `<div class="code-block-box">
<div class="code-lang-label">${lang}</div>
<pre><code${codeAttrs}><span${spanAttrs}>${codeContent}</span></code></pre>
</div>`;
}
);
//Deepseek
html = html.replace(
/<div class="md-code-block[^"]*">[\s\S]*?<span class="d813de27">([^<]+)<\/span>[\s\S]*?<pre>([\s\S]*?)<\/pre>[\s\S]*?<\/div>/gi,
function(match, lang, codeContent) {
// lang = "bash", "haskell" wait
// codeContent = complete code(Include <span> Label)
return `<div class="code-block-box">
<div class="code-lang-label">${lang}</div>
<pre>${codeContent}</pre>
</div>`;
}
);
//Grok
// Grokcode block capture(Contains language tags)
html = html.replace(
/<div[^>]*class="[^"]*@container\/code-block[^"]*"[^>]*>[\s\S]*?<span class="font-mono text-xs">([^<]+)<\/span>[\s\S]*?<pre[^>]*class="shiki[^"]*"[^>]*>\s*<code[^>]*>([\s\S]*?)<\/code>\s*<\/pre>[\s\S]*?<\/div>/gi,
function(match, lang, codeContent) {
return `<div class="code-block-box">
<div class="code-lang-label">${lang.trim()}</div>
<pre><code>${codeContent}</code></pre>
</div>`;
}
);
// Gemini
// Gemini(Bard / Gemini)code block capture
html = html.replace(
/<div[^>]*class="[^"]*\bcode-block\b[^"]*"[^>]*>[\s\S]*?<pre[^>]*>[\s\S]*?<code[^>]*class="[^"]*\bcode-container\b[^"]*"[^>]*>([\s\S]*?)<\/code>[\s\S]*?<\/pre>[\s\S]*?<\/div>/gi,
function(match, codeContent) {
// Gemini No language provided,Fill in by default "text" Or you can fill in "plain"
const lang = "text";
return `
<div class="code-block-box">
<div class="code-lang-label">${lang}</div>
<pre><code class="language-${lang}">${codeContent}</code></pre>
</div>
`;
}
);
// Perplexity.ai Code block parsing
html = html.replace(
/<div class="w-full md:max-w-\[90vw\]">[\s\S]*?<div data-testid="code-language-indicator"[^>]*>([^<]+)<\/div>[\s\S]*?<code[^>]*>([\s\S]*?)<\/code>[\s\S]*?<\/div>\s*<\/pre>\s*<\/div>/gi,
function(match, lang, codeContent) {
// extract Perplexity code content:code the first in <span> content inside
const codeMatch = codeContent.match(/<span[^>]*>([\s\S]*?)<\/span>/);
const innerCode = codeMatch ? codeMatch[1] : codeContent;
return `
<div class="code-block-box">
<div class="code-lang-label">${lang.trim()}</div>
<pre><code class="language-${lang.trim()}">${innerCode}</code></pre>
</div>`;
}
);
//Poe
// Poe Code block parsing
html = html.replace(
/<div class="MarkdownCodeBlock_container__[^"]+">[\s\S]*?<div class="MarkdownCodeBlock_languageName__[^"]+">([^<]+)<\/div>[\s\S]*?<pre[^>]*>[\s\S]*?<code[^>]*>([\s\S]*?)<\/code>[\s\S]*?<\/pre>[\s\S]*?<\/div>/gi,
function(match, lang, codeContent) {
// Poe of <code> There may be span,Need to extract pure internal code
const codeMatch = codeContent.match(/<span[^>]*>([\s\S]*?)<\/span>/);
const innerCode = codeMatch ? codeMatch[1] : codeContent;
return `
<div class="code-block-box">
<div class="code-lang-label">${lang.trim()}</div>
<pre><code class="language-${lang.trim()}">${innerCode}</code></pre>
</div>`;
}
);
return html;
}
const renderedContent = messages.map((msg, i) => {
const roleName = `Message ${i + 1}`;
return enhanceCodeBlocks(`
<div class=\"message\">\n <div class=\"message-header\">${roleName}</div>\n <div class=\"message-content\">${msg.content}</div>\n </div>`);
}).join('');
// Dynamically load templates
//const templateUrl = chrome.runtime.getURL('template.html');
//let template = await fetch(templateUrl).then(r => r.text());
let template = TEMPLATE_HTML;
// replace placeholder
template = template.replace(/{{title}}/g, title)
.replace(/{{exportTime}}/g, exportTime)
.replace(/{{platform}}/g, platform)
.replace(/{{content}}/g, renderedContent);
return template;
}
function downloadHtml(filename, html) {
const blob = new Blob([html], { type: 'text/html;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 10000);
}
function sanitizeFilename(name) {
return String(name || 'chat')
.replace(/[<>:"/\\|?*]/g, '_')
.replace(/\s+/g, ' ')
.trim()
.slice(0, 120);
}
async function exportChatAsync() {
const platform = detectPlatform();
const exportTime = formatExportTime();
const title = getTitleFallback();
const messages = await gatherMessages();
const html = await buildHTMLAsync({ title, exportTime, platform, messages });
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
const filename = `${timestamp}_${sanitizeFilename(title)}.html`;
downloadHtml(filename, html);
}
exportChatAsync().then(() => {
console.log('✅ Universal Chat Exporter: exported HTML');
}).catch(e => {
console.error('❌ Universal Chat Exporter error:', e);
alert('Export failed:' + e);
});
})();