forked from GoogleChromeLabs/link-to-text-fragment
-
Notifications
You must be signed in to change notification settings - Fork 0
/
offscreen.js
50 lines (47 loc) · 1.52 KB
/
offscreen.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
// eslint-disable-next-line no-undef
const browser = chrome || browser;
const copyLink = async (linkStyle, url, selectedText, html, linkText) => {
// Try to use the Async Clipboard API with fallback to the legacy API.
try {
const {state} = await navigator.permissions.query({
name: 'clipboard-write',
});
if (state !== 'granted') {
throw new Error('Clipboard permission not granted');
}
const clipboardItems = {
'text/plain': new Blob([url], {type: 'text/plain'}),
};
if (linkStyle === 'rich') {
clipboardItems['text/html'] = new Blob(
[`<a href="${url}">${selectedText}</a>`],
{
type: 'text/html',
},
);
} else if (linkStyle === 'rich_plus_raw') {
clipboardItems['text/html'] = new Blob(
[`${html} <a href="${url}">${linkText}</a>`],
{type: 'text/html'},
);
}
const clipboardData = [new ClipboardItem(clipboardItems)];
await navigator.clipboard.write(clipboardData);
} catch (err) {
console.error(err.name, err.message);
const textArea = document.createElement('textarea');
document.body.append(textArea);
textArea.textContent = url;
textArea.select();
document.execCommand('copy');
textArea.remove();
}
};
browser.runtime.onMessage.addListener((message) => {
if (message.target !== 'offscreen') {
return;
}
const {linkStyle, url, selectedText, html, linkText} = message.data;
copyLink(linkStyle, url, selectedText, html, linkText);
return true;
});