-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
61 lines (58 loc) · 2.13 KB
/
content.js
File metadata and controls
61 lines (58 loc) · 2.13 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
const script = document.createElement('script');
script.src = chrome.runtime.getURL('inject.js');
script.type = 'text/javascript';
(document.head || document.documentElement).appendChild(script);
chrome.runtime.onMessage.addListener((message) => {
if (message.type === 'COPY_REPOST_URL_REQUEST') {
window.postMessage({ type: 'EXECUTE_COPY_FROM_INJECT' }, '*');
}
});
window.addEventListener('message', (event) => {
if (event.source !== window || !event.data || typeof event.data.type !== 'string') return;
const type = event.data.type;
if (type === 'UPDATE_CONTEXT_MENU_STATE') {
chrome.runtime.sendMessage({ type: 'UPDATE_CONTEXT_MENU', enabled: event.data.enabled });
return;
}
if (type === 'GET_I18N_MESSAGE') {
const message = chrome.i18n.getMessage(event.data.key) || '';
window.postMessage({ type: 'I18N_MESSAGE_RESULT', key: event.data.key, message: message }, '*');
return;
}
if (type === 'REPOST_URL_TO_COPY') {
const url = event.data.url;
if (typeof url !== 'string' || !url) {
const msg = chrome.i18n.getMessage('copyFailGeneric') || 'Copy failed';
window.postMessage({ type: 'I18N_MESSAGE_RESULT', message: msg }, '*');
return;
}
copyTextToClipboard(url).catch(() => {
const msg = chrome.i18n.getMessage('copyFailGeneric') || 'Copy failed. Please right-click on the repost again.';
window.postMessage({ type: 'I18N_MESSAGE_RESULT', message: msg }, '*');
});
return;
}
});
function copyTextToClipboard(text) {
if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
return navigator.clipboard.writeText(text);
}
return new Promise((resolve, reject) => {
try {
const ta = document.createElement('textarea');
ta.value = text;
ta.style.position = 'fixed';
ta.style.left = '-9999px';
ta.setAttribute('readonly', '');
document.body.appendChild(ta);
ta.focus();
ta.select();
const ok = document.execCommand('copy');
document.body.removeChild(ta);
if (ok) resolve();
else reject(new Error('execCommand failed'));
} catch (e) {
reject(e);
}
});
}