RemoveBgExtensionChrome/contents/image_editor.js

86 lines
2.6 KiB
JavaScript

if (
["127.0.0.1", "localhost", "stage-editor.danielvu.com"].includes(
location.hostname
)
) {
let ROOT_KEY = "image_editor";
let _SELECTOR_BUTTON_ID = "btn_trigger_remove_bg_";
// INIT
window.addEventListener("load", async () => {
cloneButton();
});
// LISTEN event 🎧🎧🎧
chrome.runtime.onMessage.addListener(function (res, sendResponse) {
if (res.action === ROOT_KEY + "__has_capcha") {
alert("Has capcha! Please select it on remove.bg and go home remove.bg, Thanks!");
}
if (res.action === ROOT_KEY + "__save_image") {
const imageUrl = res.payload.url;
const filename = imageUrl.substring(imageUrl.lastIndexOf('/') + 1);
fetch(imageUrl)
.then(responseImage => responseImage.blob())
.then(blob => {
const file = new File([blob], filename, { type: blob.type });
const fileList = new DataTransfer();
const fileInput = document.querySelector(`#file_${res.payload.id}`)
fileList.items.add(file);
fileInput.files = fileList.files;
fileInput.dispatchEvent(new Event('change'));
})
.catch(error => {
console.error('Error fetching the image:', error);
});
}
if (res.action === ROOT_KEY + "__loading") {
if (res.status) {
document
.querySelectorAll(`[id^=clone__${_SELECTOR_BUTTON_ID}]`)
?.forEach((btn) => (btn.disabled = true));
} else {
document
.querySelectorAll(`[id^=clone__${_SELECTOR_BUTTON_ID}]`)
?.forEach((btn) => (btn.disabled = false));
}
}
});
function cloneButton() {
window.$intervalCloneButton = setInterval(() => {
const selector = `[id^="${_SELECTOR_BUTTON_ID}"]:not([data-has_clone="true"])`;
document.querySelectorAll(selector)?.forEach((btn) => {
const cloneEl = btn.cloneNode(true);
cloneEl.id = "clone__" + cloneEl.id;
cloneEl.classList.value = cloneEl.classList.value.replace(
"purple",
"blue"
);
cloneEl.querySelector(".q-btn__content ").textContent =
"remove.bg extension";
cloneEl.addEventListener("click", function () {
handleClick(this);
});
btn.after(cloneEl);
btn.setAttribute("data-has_clone", true);
});
}, 1000);
}
function handleClick(btn) {
const id = btn.getAttribute("data-id");
const urlImg = btn.getAttribute("data-image");
btn.disabled = true;
chrome.runtime.sendMessage({
action: "remove_bg__execute",
payload: {
id: parseInt(id),
url: urlImg,
},
});
}
}