-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
96 lines (82 loc) · 2.51 KB
/
background.js
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
'use strict';
var legacyBrowser = false;
function escapeHTML (html) {
return html
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"')
.replaceAll("'", ''');
}
function htmlLink(url, text) {
return `<a href="${escapeHTML(url)}">${escapeHTML(text)}</a>`;
}
function markdownLink(url, text) {
return `[${escapeHTML(text)}](${escapeHTML(url)})`;
}
function copyToClipboard (links) {
let htmlValue = '';
let textValue = '';
if (links.length === 1) {
htmlValue = htmlLink(links[0].url, links[0].text);
textValue = markdownLink(links[0].url, links[0].text);
} else {
htmlValue += '<ul>\n';
for (let link of links) {
htmlValue += `<li>${htmlLink(link.url, link.text)}</li>\n`;
textValue += `- ${markdownLink(link.url, link.text)}\n`;
}
htmlValue += '</ul>\n';
}
if (!legacyBrowser) {
let item = new ClipboardItem({'text/html': htmlValue, 'text/plain': textValue});
navigator.clipboard.write([item])
.catch(error => console.error(`Copy link failed: ${error.message}`));
} else {
let legacyListener = function (event) {
event.clipboardData.setData('text/html', htmlValue);
event.clipboardData.setData('text/plain', textValue);
event.preventDefault();
}
document.addEventListener('copy', legacyListener);
document.execCommand('copy');
document.removeEventListener('copy', legacyListener);
}
}
browser.commands.onCommand.addListener((command, tab) => {
if (command !== COMMAND_ID) {
return;
}
if (tab !== undefined) {
browser.tabs.sendMessage(tab.id, {'type': LINK_REQUEST});
} else {
browser.tabs.query({'active': true, 'currentWindow': true}).then(tabs => {
browser.tabs.sendMessage(tabs[0].id, {'type': LINK_REQUEST});
});
}
});
browser.contextMenus.create({
id: COMMAND_ID,
title: browser.i18n.getMessage('menuItemTitle'),
contexts: ['link', 'page', 'selection', 'tab'],
}
);
browser.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId !== COMMAND_ID) {
return;
}
if (info.hasOwnProperty('linkUrl') && info.hasOwnProperty('linkText')) {
copyToClipboard([{'url': info.linkUrl, 'text': info.linkText}]);
}
else {
browser.tabs.sendMessage(tab.id, {'type': LINK_REQUEST});
}
});
browser.runtime.onMessage.addListener(message => {
if (message.type === LINK_RESPONSE) {
copyToClipboard(message.links);
}
});
if (typeof ClipboardItem === 'undefined') {
legacyBrowser = true;
}