-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
309 lines (260 loc) · 8.67 KB
/
Copy pathpopup.js
File metadata and controls
309 lines (260 loc) · 8.67 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
const SUPPORT_URL = 'https://buymeacoffee.com/ivomartins';
const saveBtn = document.getElementById('saveBtn');
const copyBtn = document.getElementById('copyBtn');
const statusEl = document.getElementById('status');
const supportLink = document.getElementById('supportLink');
initPopup();
function initPopup() {
restoreImagePreference();
document.querySelectorAll('input[name="imgOpt"]').forEach((radio) => {
radio.addEventListener('change', () => {
chrome.storage.local.set({ imageOption: getSelectedImageOption() });
});
});
saveBtn.addEventListener('click', handleDownload);
copyBtn.addEventListener('click', handleCopy);
supportLink.addEventListener('click', (event) => {
event.preventDefault();
chrome.tabs.create({ url: SUPPORT_URL });
});
}
async function restoreImagePreference() {
try {
const { imageOption = 'url' } = await chrome.storage.local.get('imageOption');
const savedOption = document.querySelector(`input[name="imgOpt"][value="${imageOption}"]`);
if (savedOption) {
savedOption.checked = true;
}
} catch (err) {
console.warn('Could not restore image preference:', err);
}
}
async function handleDownload() {
const imageOption = getSelectedImageOption();
await chrome.storage.local.set({ imageOption });
await runWithBusyState(async () => {
setStatus('Converting page...');
const data = await convertActiveTab(imageOption);
setStatus('Preparing download...');
if (imageOption === 'zip') {
const result = await createZipAndDownload(data);
const imageSummary = result.totalImages
? ` ${result.downloadedImages} of ${result.totalImages} images bundled.`
: ' No images found.';
setStatus(`Saved ZIP.${imageSummary}`);
} else {
await downloadMarkdown(data.markdown, data.fileBase);
setStatus('Saved Markdown with source URLs.');
}
});
}
async function handleCopy() {
await runWithBusyState(async () => {
setStatus('Converting page...');
const data = await convertActiveTab('url');
await navigator.clipboard.writeText(data.markdown);
setStatus('Copied Markdown with source URLs.');
});
}
async function runWithBusyState(task) {
saveBtn.disabled = true;
copyBtn.disabled = true;
try {
await task();
} catch (err) {
setStatus(`Error: ${friendlyErrorMessage(err)}`);
console.error('Full Error Object:', err);
} finally {
saveBtn.disabled = false;
copyBtn.disabled = false;
}
}
async function convertActiveTab(imageOption) {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (!tab || !tab.id) {
throw new Error('No active tab found.');
}
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['./lib/Readability.js', './lib/turndown.js']
});
const capturedDate = formatLocalDate(new Date());
const results = await chrome.scripting.executeScript({
target: { tabId: tab.id },
func: processPageInsideTab,
args: [imageOption, capturedDate]
});
if (!results || !results[0] || !results[0].result) {
throw new Error('The conversion script returned no data.');
}
const data = results[0].result;
if (data.error) {
throw new Error(data.error);
}
if (!data.markdown) {
throw new Error('Markdown content is empty.');
}
return data;
}
function getSelectedImageOption() {
return document.querySelector('input[name="imgOpt"]:checked').value;
}
function setStatus(message) {
statusEl.innerText = message;
}
function friendlyErrorMessage(err) {
const message = err && err.message ? err.message : String(err);
if (message.includes('Cannot access') || message.includes('The extensions gallery cannot be scripted')) {
return 'Chrome does not allow extensions to convert this page.';
}
if (message.includes('clipboard')) {
return 'Could not copy to clipboard. Try downloading instead.';
}
return message;
}
function formatLocalDate(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
// This function runs inside the active webpage.
function processPageInsideTab(mode, capturedDate) {
try {
if (typeof Readability === 'undefined') {
return { error: 'Readability library not found on page.' };
}
const TurndownClass = typeof Turndown !== 'undefined'
? Turndown
: (typeof TurndownService !== 'undefined' ? TurndownService : null);
if (!TurndownClass) {
return { error: 'Turndown library not found on page.' };
}
const docClone = document.cloneNode(true);
const article = new Readability(docClone).parse();
const contentHtml = article ? article.content : document.body.innerHTML;
const rawTitle = (article && article.title) || document.title || document.location.hostname || 'Webpage';
const title = String(rawTitle).replace(/\s+/g, ' ').trim() || 'Webpage';
const sourceUrl = document.location.href;
const turndownService = new TurndownClass({
headingStyle: 'atx',
codeBlockStyle: 'fenced'
});
const imagesToDownload = [];
let finalHtml = contentHtml;
if (mode === 'zip') {
const tempDiv = document.createElement('div');
tempDiv.innerHTML = contentHtml;
tempDiv.querySelectorAll('img').forEach((img, index) => {
const rawSrc = img.currentSrc || img.src || img.getAttribute('src');
const absoluteUrl = resolveUrl(rawSrc);
if (!absoluteUrl || !absoluteUrl.startsWith('http')) {
return;
}
const filename = `img_${index}.${getImageExtension(absoluteUrl)}`;
imagesToDownload.push({ url: absoluteUrl, filename });
img.setAttribute('src', `./images/${filename}`);
img.removeAttribute('srcset');
});
finalHtml = tempDiv.innerHTML;
}
const contentMarkdown = turndownService.turndown(finalHtml).trim();
const fileBase = buildFileBase(title, sourceUrl, capturedDate);
const markdown = [
'---',
`title: "${escapeYaml(title)}"`,
`source: "${escapeYaml(sourceUrl)}"`,
`captured: "${capturedDate}"`,
'---',
'',
`# ${title}`,
'',
contentMarkdown
].join('\n');
return {
markdown,
title,
sourceUrl,
capturedDate,
fileBase,
images: imagesToDownload
};
} catch (e) {
return { error: e.message };
}
function resolveUrl(value) {
if (!value) {
return '';
}
try {
return new URL(value, document.baseURI).href;
} catch (e) {
return '';
}
}
function getImageExtension(url) {
try {
const pathname = new URL(url).pathname;
const match = pathname.match(/\.([a-z0-9]{2,4})$/i);
return match ? match[1].toLowerCase() : 'png';
} catch (e) {
return 'png';
}
}
function buildFileBase(titleValue, sourceValue, dateValue) {
let slug = slugify(titleValue);
if (!slug) {
try {
slug = slugify(new URL(sourceValue).hostname);
} catch (e) {
slug = 'webpage';
}
}
return `${dateValue}_${slug.slice(0, 80)}`;
}
function slugify(value) {
return String(value || '')
.normalize('NFKD')
.replace(/[\u0300-\u036f]/g, '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
}
function escapeYaml(value) {
return String(value || '').replace(/\s+/g, ' ').trim().replace(/\\/g, '\\\\').replace(/"/g, '\\"');
}
}
async function createZipAndDownload(data) {
if (typeof JSZip === 'undefined') {
throw new Error('JSZip library not loaded. Check if lib/jszip.js exists.');
}
const zip = new JSZip();
const bundleFolder = zip.folder(data.fileBase);
bundleFolder.file(`${data.fileBase}.md`, data.markdown);
let downloadedImages = 0;
const totalImages = data.images ? data.images.length : 0;
if (totalImages > 0) {
const imgFolder = bundleFolder.folder('images');
for (const img of data.images) {
try {
const resp = await fetch(img.url);
if (resp.ok) {
const blob = await resp.blob();
imgFolder.file(img.filename, blob);
downloadedImages += 1;
}
} catch (e) {
console.warn('Could not fetch image:', img.url);
}
}
}
const content = await zip.generateAsync({ type: 'blob' });
const url = URL.createObjectURL(content);
await chrome.downloads.download({ url, filename: `${data.fileBase}.zip` });
return { downloadedImages, totalImages };
}
async function downloadMarkdown(markdown, fileBase) {
const blob = new Blob([markdown], { type: 'text/markdown' });
const url = URL.createObjectURL(blob);
await chrome.downloads.download({ url, filename: `${fileBase}.md` });
}