-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
74 lines (74 loc) · 2.45 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
browser.contextMenus.create({
id: "copy-alt-text-to-clipboard",
title: "Copy Alt Text",
contexts: ["image"],
});
const notify = (title, message) =>
browser.notifications.create({
type: "basic",
iconUrl: browser.extension.getURL("icons/96.png"),
title,
message,
});
browser.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "copy-alt-text-to-clipboard") {
browser.tabs
.executeScript(tab.id, {
code: '[...document.querySelectorAll("img")].map(({src,alt,srcset}) => ({src,alt,srcset}))',
})
.then((images) => {
const image = images[0].find((e) =>
[
e.src,
...parseSrcset(e.srcset).map((e) => new URL(e.url, tab.url).href),
].includes(info.srcUrl),
);
if (!image) {
throw new Error("failed to find image in page");
}
const text = image.alt;
if (!text) {
notify("Nothing to copy.", "That image doesn’t have alt text.");
return;
}
return browser.tabs
.executeScript({
code: "typeof copyToClipboard === 'function'",
})
.then((results) => {
// The content script's last expression will be true if the function
// has been defined. If this is not the case, then we need to run
// clipboard-helper.js to define function copyToClipboard.
if (!results || results[0] !== true) {
return browser.tabs.executeScript(tab.id, {
file: "clipboard-helper.js",
});
}
})
.then(() => {
return browser.tabs.executeScript(tab.id, {
code: `copyToClipboard(${JSON.stringify(text)})`,
});
})
})
.catch((error) => {
if (tab.url.startsWith("about:")) {
notify(
"Failed to copy.",
"This page is built in to Firefox and can’t be accessed by extensions.",
);
} else if (new URL(tab.url) === "https://addons.mozilla.org") {
notify(
"Failed to copy.",
"The Firefox Add-ons website can’t be accessed by extensions.",
);
} else {
notify(
"Failed to copy.",
"Please report this (with a link to the page you’re on) at https://github.com/easrng/copy-alt-text/issues.",
);
console.error(error);
}
});
}
});