|
| 1 | +const onClick = async (url, quality, apiKey) => { |
| 2 | + const formData = new FormData(); |
| 3 | + formData.append("image_url", url); |
| 4 | + formData.append("size", quality); |
| 5 | + try { |
| 6 | + const resp = await fetch("https://api.remove.bg/v1.0/removebg", { |
| 7 | + method: "POST", |
| 8 | + body: formData, |
| 9 | + headers: { |
| 10 | + "X-Api-Key": apiKey, |
| 11 | + }, |
| 12 | + }); |
| 13 | + |
| 14 | + if (resp.status === 200) { |
| 15 | + const blob = new Blob([await resp.blob()]); |
| 16 | + const blobUrl = window.URL.createObjectURL(blob); |
| 17 | + const link = document.createElement("a"); |
| 18 | + link.href = blobUrl; |
| 19 | + link.setAttribute( |
| 20 | + "download", |
| 21 | + `removebg_${quality}_${url.split("/").pop()}` |
| 22 | + ); |
| 23 | + document.body.appendChild(link); |
| 24 | + link.click(); |
| 25 | + link.parentNode.removeChild(link); |
| 26 | + window.URL.revokeObjectURL(blobUrl); |
| 27 | + } else { |
| 28 | + const json = await resp.json(); |
| 29 | + console.log(json); |
| 30 | + browser.notifications.create({ |
| 31 | + title: "Failed to process image", |
| 32 | + message: json?.errors?.[0]?.title || "Unknown error", |
| 33 | + type: "basic", |
| 34 | + }); |
| 35 | + } |
| 36 | + } catch (e) { |
| 37 | + console.error("Some error:", e); |
| 38 | + } |
| 39 | +}; |
| 40 | + |
| 41 | +const createMenuItems = (apiKey) => { |
| 42 | + browser.contextMenus.removeAll(); |
| 43 | + |
| 44 | + if (apiKey) { |
| 45 | + browser.contextMenus.create({ |
| 46 | + id: "removebg-preview", |
| 47 | + title: "Preview Quality (max. 0.25 megapixels)", |
| 48 | + contexts: ["image"], |
| 49 | + }); |
| 50 | + |
| 51 | + browser.contextMenus.create({ |
| 52 | + id: "removebg-hq", |
| 53 | + title: "High Quality (max. 25 megapixels)", |
| 54 | + contexts: ["image"], |
| 55 | + }); |
| 56 | + |
| 57 | + browser.contextMenus.onClicked.addListener(async (info) => { |
| 58 | + if (info.mediaType !== "image") return; |
| 59 | + |
| 60 | + onClick( |
| 61 | + info.srcUrl, |
| 62 | + info.menuItemId === "removebg-hq" ? "auto" : "preview", |
| 63 | + apiKey |
| 64 | + ); |
| 65 | + }); |
| 66 | + } else { |
| 67 | + browser.contextMenus.create({ |
| 68 | + id: "removebg-apikey", |
| 69 | + title: "Remove.bg - Add API Key", |
| 70 | + contexts: ["image"], |
| 71 | + }); |
| 72 | + |
| 73 | + browser.contextMenus.onClicked.addListener((info) => { |
| 74 | + if (info.mediaType !== "image") return; |
| 75 | + |
| 76 | + if (info.menuItemId === "removebg-apikey") { |
| 77 | + browser.runtime.openOptionsPage(); |
| 78 | + } |
| 79 | + }); |
| 80 | + } |
| 81 | +}; |
| 82 | + |
| 83 | +browser.storage.local.get("removebgapikey").then((resp) => { |
| 84 | + const apiKey = resp.removebgapikey; |
| 85 | + createMenuItems(apiKey); |
| 86 | +}); |
0 commit comments