-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremovebg-firefox.js
More file actions
86 lines (77 loc) · 2.21 KB
/
removebg-firefox.js
File metadata and controls
86 lines (77 loc) · 2.21 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
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
const onClick = async (url, quality, apiKey) => {
const formData = new FormData();
formData.append("image_url", url);
formData.append("size", quality);
try {
const resp = await fetch("https://api.remove.bg/v1.0/removebg", {
method: "POST",
body: formData,
headers: {
"X-Api-Key": apiKey,
},
});
if (resp.status === 200) {
const blob = new Blob([await resp.blob()]);
const blobUrl = window.URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = blobUrl;
link.setAttribute(
"download",
`removebg_${quality}_${url.split("/").pop()}`
);
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
window.URL.revokeObjectURL(blobUrl);
} else {
const json = await resp.json();
console.log(json);
browser.notifications.create({
title: "Failed to process image",
message: json?.errors?.[0]?.title || "Unknown error",
type: "basic",
});
}
} catch (e) {
console.error("Some error:", e);
}
};
const createMenuItems = (apiKey) => {
browser.contextMenus.removeAll();
if (apiKey) {
browser.contextMenus.create({
id: "removebg-preview",
title: "Preview Quality (max. 0.25 megapixels)",
contexts: ["image"],
});
browser.contextMenus.create({
id: "removebg-hq",
title: "High Quality (max. 25 megapixels)",
contexts: ["image"],
});
browser.contextMenus.onClicked.addListener(async (info) => {
if (info.mediaType !== "image") return;
onClick(
info.srcUrl,
info.menuItemId === "removebg-hq" ? "auto" : "preview",
apiKey
);
});
} else {
browser.contextMenus.create({
id: "removebg-apikey",
title: "Remove.bg - Add API Key",
contexts: ["image"],
});
browser.contextMenus.onClicked.addListener((info) => {
if (info.mediaType !== "image") return;
if (info.menuItemId === "removebg-apikey") {
browser.runtime.openOptionsPage();
}
});
}
};
browser.storage.local.get("removebgapikey").then((resp) => {
const apiKey = resp.removebgapikey;
createMenuItems(apiKey);
});