forked from Marverlises/ChatGPT-To-Markdown-google-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatGPT-To-Markdown-UserScript.js
More file actions
342 lines (306 loc) · 12.2 KB
/
ChatGPT-To-Markdown-UserScript.js
File metadata and controls
342 lines (306 loc) · 12.2 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
// ==UserScript==
// @name ChatGPT to Markdown Exporter
// @version 1.0
// @description Export chat history from ChatGPT and Grok websites to Markdown format.
// @author ChingyuanCheng //origin from: Marverlises
// @match https://chatgpt.com/*
// @match https://*.openai.com/*
// @match https://grok.com/*
// @grant none
// ==/UserScript==
(function() {
// Select chat elements based on the website
function getConversationElements() {
const currentUrl = window.location.href;
if (currentUrl.includes("openai.com") || currentUrl.includes("chatgpt.com")) {
return document.querySelectorAll('div.flex.flex-grow.flex-col.max-w-full');
} else if (currentUrl.includes("grok.com")) {
return document.querySelectorAll('div.message-bubble');
}
return [];
}
// Convert HTML to Markdown
function htmlToMarkdown(html) {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
// Handle formulas
doc.querySelectorAll('span.katex-html').forEach(element => element.remove());
doc.querySelectorAll('mrow').forEach(mrow => mrow.remove());
doc.querySelectorAll('annotation[encoding="application/x-tex"]').forEach(element => {
if (element.closest('.katex-display')) {
const latex = element.textContent;
element.replaceWith(`\n$$\n${latex}\n$$\n`);
} else {
const latex = element.textContent;
element.replaceWith(`$${latex}$`);
}
});
// Bold text
doc.querySelectorAll('strong, b').forEach(bold => {
bold.parentNode.replaceChild(document.createTextNode(`**${bold.textContent}**`), bold);
});
// Italic text
doc.querySelectorAll('em, i').forEach(italic => {
italic.parentNode.replaceChild(document.createTextNode(`*${italic.textContent}*`), italic);
});
// Inline code
doc.querySelectorAll('p code').forEach(code => {
code.parentNode.replaceChild(document.createTextNode(`\`${code.textContent}\``), code);
});
// Links
doc.querySelectorAll('a').forEach(link => {
link.parentNode.replaceChild(document.createTextNode(`[${link.textContent}](${link.href})`), link);
});
// Images
doc.querySelectorAll('img').forEach(img => {
img.parentNode.replaceChild(document.createTextNode(``), img);
});
// Code blocks
doc.querySelectorAll('pre').forEach(pre => {
const codeType = pre.querySelector('div > div:first-child')?.textContent || '';
const markdownCode = pre.querySelector('div > div:nth-child(3) > code')?.textContent || pre.textContent;
pre.innerHTML = `\n\`\`\`${codeType}\n${markdownCode}\`\`\`\n`;
});
// Unordered lists
doc.querySelectorAll('ul').forEach(ul => {
let markdown = '';
ul.querySelectorAll(':scope > li').forEach(li => {
markdown += `- ${li.textContent.trim()}\n`;
});
ul.parentNode.replaceChild(document.createTextNode('\n' + markdown.trim()), ul);
});
// Ordered lists
doc.querySelectorAll('ol').forEach(ol => {
let markdown = '';
ol.querySelectorAll(':scope > li').forEach((li, index) => {
markdown += `${index + 1}. ${li.textContent.trim()}\n`;
});
ol.parentNode.replaceChild(document.createTextNode('\n' + markdown.trim()), ol);
});
// Headers
for (let i = 1; i <= 6; i++) {
doc.querySelectorAll(`h${i}`).forEach(header => {
header.parentNode.replaceChild(document.createTextNode('\n' + `${'#'.repeat(i)} ${header.textContent}\n`), header);
});
}
// Paragraphs
doc.querySelectorAll('p').forEach(p => {
p.parentNode.replaceChild(document.createTextNode('\n' + p.textContent + '\n'), p);
});
// Tables
doc.querySelectorAll('table').forEach(table => {
let markdown = '';
table.querySelectorAll('thead tr').forEach(tr => {
tr.querySelectorAll('th').forEach(th => {
markdown += `| ${th.textContent} `;
});
markdown += '|\n';
tr.querySelectorAll('th').forEach(() => {
markdown += '| ---- ';
});
markdown += '|\n';
});
table.querySelectorAll('tbody tr').forEach(tr => {
tr.querySelectorAll('td').forEach(td => {
markdown += `| ${td.textContent} `;
});
markdown += '|\n';
});
table.parentNode.replaceChild(document.createTextNode('\n' + markdown.trim() + '\n'), table);
});
let markdown = doc.body.innerHTML.replace(/<[^>]*>/g, '');
markdown = markdown.replaceAll(/- >/g, '- $\\gt$')
.replaceAll(/>/g, '>')
.replaceAll(/</g, '<')
.replaceAll(/≥/g, '>=')
.replaceAll(/≤/g, '<=')
.replaceAll(/≠/g, '\\neq');
return markdown.trim();
}
// Download content as a file
function download(data, filename, type) {
const file = new Blob([data], { type: type });
const a = document.createElement('a');
const url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
// Show export modal with Markdown content
function showExportModal() {
let markdownContent = "";
const allElements = getConversationElements();
for (let i = 0; i < allElements.length; i += 2) {
if (!allElements[i + 1]) break;
let userText = allElements[i].textContent.trim();
let answerHtml = allElements[i + 1].innerHTML.trim();
userText = htmlToMarkdown(userText);
answerHtml = htmlToMarkdown(answerHtml);
const isGrok = window.location.href.includes("grok.com");
markdownContent += `\n# User Question\n${userText}\n# ${isGrok ? 'Grok' : 'ChatGPT'}\n${answerHtml}`;
}
markdownContent = markdownContent.replace(/&/g, '&');
if (!markdownContent) {
alert("No conversation content found.");
return;
}
// Create modal
const modal = document.createElement('div');
modal.id = 'markdown-modal';
Object.assign(modal.style, {
position: 'fixed',
top: '0',
left: '0',
width: '100%',
height: '100%',
backgroundColor: 'rgba(0, 0, 0, 0.5)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
zIndex: '1000'
});
const modalContent = document.createElement('div');
Object.assign(modalContent.style, {
backgroundColor: '#fff',
color: '#000',
padding: '20px',
borderRadius: '8px',
width: '50%',
height: '80%',
display: 'flex',
flexDirection: 'column',
boxShadow: '0 2px 10px rgba(0,0,0,0.1)',
overflow: 'hidden'
});
const textarea = document.createElement('textarea');
textarea.value = markdownContent;
Object.assign(textarea.style, {
flex: '1',
resize: 'none',
width: '100%',
padding: '10px',
fontSize: '14px',
fontFamily: 'monospace',
marginBottom: '10px',
boxSizing: 'border-box',
color: '#000',
backgroundColor: '#f9f9f9',
border: '1px solid #ccc',
borderRadius: '4px'
});
textarea.setAttribute('readonly', true);
const buttonContainer = document.createElement('div');
Object.assign(buttonContainer.style, {
display: 'flex',
justifyContent: 'flex-end'
});
const copyButton = document.createElement('button');
copyButton.textContent = 'Copy';
Object.assign(copyButton.style, {
padding: '8px 16px',
fontSize: '14px',
cursor: 'pointer',
backgroundColor: '#28A745',
color: '#fff',
border: 'none',
borderRadius: '4px',
marginRight: '10px'
});
const downloadButton = document.createElement('button');
downloadButton.textContent = 'Download';
Object.assign(downloadButton.style, {
padding: '8px 16px',
fontSize: '14px',
cursor: 'pointer',
backgroundColor: '#007BFF',
color: '#fff',
border: 'none',
borderRadius: '4px',
marginRight: '10px'
});
const closeButton = document.createElement('button');
closeButton.textContent = 'Close';
Object.assign(closeButton.style, {
padding: '8px 16px',
fontSize: '14px',
cursor: 'pointer',
backgroundColor: '#DC3545',
color: '#fff',
border: 'none',
borderRadius: '4px'
});
buttonContainer.appendChild(copyButton);
buttonContainer.appendChild(downloadButton);
buttonContainer.appendChild(closeButton);
modalContent.appendChild(textarea);
modalContent.appendChild(buttonContainer);
modal.appendChild(modalContent);
document.body.appendChild(modal);
// Event listeners for buttons
copyButton.addEventListener('click', () => {
textarea.select();
navigator.clipboard.writeText(textarea.value)
.then(() => {
copyButton.textContent = 'Copied';
setTimeout(() => copyButton.textContent = 'Copy', 2000);
})
.catch(err => console.error('Copy failed', err));
});
downloadButton.addEventListener('click', () => {
download(markdownContent, 'chat-export.md', 'text/markdown');
});
closeButton.addEventListener('click', () => {
document.body.removeChild(modal);
});
// Close modal with Escape key or click outside
const escListener = (e) => {
if (e.key === 'Escape' && document.getElementById('markdown-modal')) {
document.body.removeChild(modal);
document.removeEventListener('keydown', escListener);
}
};
document.addEventListener('keydown', escListener);
modal.addEventListener('click', (e) => {
if (e.target === modal) {
document.body.removeChild(modal);
document.removeEventListener('keydown', escListener);
}
});
}
// Create the export button on the page
function createExportButton() {
const exportButton = document.createElement('button');
exportButton.textContent = 'Export Chat';
exportButton.id = 'export-chat';
const styles = {
position: 'fixed',
height: '36px',
top: '10px',
right: '35%',
zIndex: '10000',
padding: '10px',
backgroundColor: '#4cafa3',
color: 'white',
border: 'none',
borderRadius: '5px',
cursor: 'pointer',
textAlign: 'center',
lineHeight: '16px'
};
Object.assign(exportButton.style, styles);
document.body.appendChild(exportButton);
exportButton.addEventListener('click', showExportModal);
}
// Initialize button and periodically check its presence
createExportButton();
setInterval(() => {
if (!document.getElementById('export-chat')) {
createExportButton();
}
}, 1000);
})();