-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
53 lines (51 loc) · 1.99 KB
/
content.js
File metadata and controls
53 lines (51 loc) · 1.99 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
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "extractUrl") {
navigator.clipboard.read().then(clipboardItems => {
for (let clipboardItem of clipboardItems) {
if (clipboardItem.types.includes('text/html')) {
clipboardItem.getType('text/html').then(blob => {
blob.text().then(html => {
const url = extractFirstUrl(html);
if (url) {
copyToClipboard(url);
sendResponse({ success: true, message: 'URL copied to clipboard!' });
} else {
sendResponse({ success: false, message: 'No URL found in clipboard data.' });
}
});
});
} else if (clipboardItem.types.includes('text/plain')) {
clipboardItem.getType('text/plain').then(blob => {
blob.text().then(text => {
const url = extractFirstUrl(text);
if (url) {
copyToClipboard(url);
sendResponse({ success: true, message: 'URL copied to clipboard!' });
} else {
sendResponse({ success: false, message: 'No URL found in clipboard data.' });
}
});
});
} else {
sendResponse({ success: false, message: 'No supported clipboard type found.' });
}
}
}).catch(err => {
console.error('Failed to read clipboard contents: ', err);
sendResponse({ success: false, message: 'Failed to read clipboard contents.' });
});
return true; // Keep the message channel open for async response
}
});
function extractFirstUrl(content) {
const urlMatch = content.match(/https?:\/\/[^\s"]+/);
return urlMatch ? urlMatch[0] : null;
}
function copyToClipboard(text) {
const tempInput = document.createElement('input');
document.body.appendChild(tempInput);
tempInput.value = text;
tempInput.select();
document.execCommand('copy');
document.body.removeChild(tempInput);
}