-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbackground.js
More file actions
349 lines (306 loc) · 9.69 KB
/
background.js
File metadata and controls
349 lines (306 loc) · 9.69 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
/**
* WebMD Background Service Worker
*
* Handles Chrome extension commands, keyboard shortcuts, and new tab creation
* for displaying converted Markdown content. This service worker runs in the
* background and coordinates between the popup, content scripts, and browser.
*/
/**
* Chrome Commands API listener for keyboard shortcuts
* Handles the global keyboard shortcut (Cmd+Shift+K / Ctrl+Shift+K)
* for converting the current page to Markdown
*/
chrome.commands.onCommand.addListener(async (command) => {
if (command === 'convert-to-markdown') {
try {
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
const activeTab = tabs[0];
// Programmatically inject required scripts into the active tab
// This ensures content scripts are available even on pages loaded
// before the extension was installed or on restricted pages
try {
await chrome.scripting.executeScript({
target: { tabId: activeTab.id },
files: [
'lib/readability.js',
'lib/turndown.js',
'lib/turndown-plugin-gfm.js',
'content.js'
]
});
} catch (e) {
// Scripts might already be injected from manifest or previous injection
// This is expected behavior and not an error condition
}
// Now send the message
chrome.tabs.sendMessage(activeTab.id, { action: 'convertToMarkdown' }, (response) => {
if (chrome.runtime.lastError) {
console.error('Error:', chrome.runtime.lastError);
return;
}
if (response && response.success) {
createMarkdownTab(response.data);
} else {
console.error('Conversion failed:', response?.error);
}
});
} catch (error) {
console.error('Command error:', error);
}
}
});
/**
* Runtime message listener for communication with content scripts and popup
* Handles requests to open new tabs with converted Markdown content
*/
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'openMarkdownTab') {
createMarkdownTab(request.data);
sendResponse({ success: true });
}
return true;
});
/**
* Creates a new browser tab displaying the converted Markdown content
* Generates a complete HTML page with styling and interactive features
* @param {Object} data - Object containing markdown string and metadata
* @param {string} data.markdown - The converted Markdown content
* @param {Object} data.metadata - Metadata about the source page
*/
function createMarkdownTab(data) {
const { markdown, metadata } = data;
// Generate a complete HTML document for displaying the Markdown
// This creates a self-contained page with embedded styles and scripts
const htmlContent = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Markdown Output</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background: #f5f5f5;
}
.container {
background: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
padding-bottom: 20px;
border-bottom: 1px solid #e0e0e0;
}
h1 {
margin: 0;
font-size: 24px;
color: #333;
}
.actions {
display: flex;
gap: 10px;
}
button {
padding: 8px 16px;
border: none;
border-radius: 4px;
font-size: 14px;
cursor: pointer;
transition: all 0.2s;
}
.copy-btn {
background: #007bff;
color: white;
}
.copy-btn:hover {
background: #0056b3;
}
.copy-btn.copied {
background: #28a745;
}
.download-btn {
background: #6c757d;
color: white;
}
.download-btn:hover {
background: #545b62;
}
.markdown-content {
font-family: 'SF Mono', Monaco, 'Cascadia Code', monospace;
font-size: 14px;
line-height: 1.6;
white-space: pre-wrap;
word-wrap: break-word;
background: #f8f9fa;
padding: 20px;
border-radius: 4px;
border: 1px solid #dee2e6;
height: 70vh;
min-height: 400px;
overflow-y: auto;
width: 100%;
box-sizing: border-box;
resize: vertical;
outline: none;
}
.markdown-content:focus {
border-color: #80bdff;
box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
}
.status {
position: fixed;
top: 20px;
right: 20px;
background: #28a745;
color: white;
padding: 10px 20px;
border-radius: 4px;
opacity: 0;
transition: opacity 0.3s;
pointer-events: none;
}
.status.show {
opacity: 1;
}
.metadata {
font-size: 12px;
color: #666;
margin-bottom: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Markdown Output</h1>
<div class="actions">
<button class="copy-btn" onclick="copyToClipboard()">Copy to Clipboard</button>
<button class="download-btn" onclick="downloadMarkdown()">Download</button>
</div>
</div>
<div class="metadata">
${metadata.title ? `<div>Source: ${metadata.title}</div>` : ''}
${metadata.author ? `<div>Author: ${metadata.author}</div>` : ''}
</div>
<textarea class="markdown-content" id="markdown-content" readonly>${markdown.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''')}</textarea>
</div>
<div class="status" id="status">Copied to clipboard!</div>
<script>
const markdownContent = ${JSON.stringify(markdown)};
// Add double-click to select all functionality
document.getElementById('markdown-content').addEventListener('dblclick', function() {
this.select();
});
// Ensure textarea is focused when clicked to enable keyboard shortcuts
document.getElementById('markdown-content').addEventListener('click', function() {
this.focus();
});
// Update the textarea with the actual markdown content (not escaped)
document.getElementById('markdown-content').value = markdownContent;
function copyToClipboard() {
// Try modern clipboard API first
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(markdownContent).then(() => {
showCopySuccess();
}).catch(err => {
console.error('Clipboard API failed:', err);
fallbackCopy();
});
} else {
// Use fallback method
fallbackCopy();
}
}
function fallbackCopy() {
// Create a temporary textarea element
const textarea = document.createElement('textarea');
textarea.value = markdownContent;
textarea.style.position = 'fixed';
textarea.style.top = '0';
textarea.style.left = '0';
textarea.style.width = '2em';
textarea.style.height = '2em';
textarea.style.padding = '0';
textarea.style.border = 'none';
textarea.style.outline = 'none';
textarea.style.boxShadow = 'none';
textarea.style.background = 'transparent';
document.body.appendChild(textarea);
textarea.focus();
textarea.select();
try {
const successful = document.execCommand('copy');
if (successful) {
showCopySuccess();
} else {
alert('Failed to copy to clipboard');
}
} catch (err) {
console.error('Fallback copy failed:', err);
alert('Failed to copy to clipboard');
}
document.body.removeChild(textarea);
}
function showCopySuccess() {
const btn = document.querySelector('.copy-btn');
const status = document.getElementById('status');
btn.textContent = 'Copied!';
btn.classList.add('copied');
status.classList.add('show');
setTimeout(() => {
btn.textContent = 'Copy to Clipboard';
btn.classList.remove('copied');
status.classList.remove('show');
}, 2000);
}
function downloadMarkdown() {
const blob = new Blob([markdownContent], { type: 'text/markdown' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'page-content.md';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// Auto-copy on load (optional)
// copyToClipboard();
</script>
</body>
</html>`;
// Create a data URL from the HTML content
// This allows us to open a fully-styled page without hosting files
const dataUrl = 'data:text/html;charset=utf-8,' + encodeURIComponent(htmlContent);
// Open the generated page in a new browser tab
chrome.tabs.create({ url: dataUrl });
}
/**
* Escapes HTML special characters to prevent XSS when displaying content
* @param {string} text - Raw text that may contain HTML characters
* @returns {string} Text with HTML characters properly escaped
*/
function escapeHtml(text) {
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, m => map[m]);
}