koboprice/lib/extractPrice.js

53 lines
1.2 KiB
JavaScript
Raw Normal View History

2024-07-14 22:36:08 +03:00
const timeout = (duration) => new Promise((r) => setTimeout(r, duration));
const observePriceOnPage = (page) =>
new Promise((res, rej) => {
timeout(5000).then(() => rej("price not found"));
2024-07-14 22:36:08 +03:00
var observer = new MutationObserver(() => {
2024-07-15 20:52:41 +03:00
const price = page?.querySelector(
2024-07-14 22:36:08 +03:00
".primary-right-container .pricing-details .active-price span",
2024-07-15 20:52:41 +03:00
)?.textContent;
2024-07-14 22:36:08 +03:00
if (price) {
l("found price", price);
observer.disconnect();
res(price);
}
});
observer.observe(page, {
attributes: true,
childList: true,
characterData: true,
subtree: true,
});
});
2024-07-15 20:52:41 +03:00
export const extractPrice = async (url) => {
2024-07-14 22:36:08 +03:00
try {
l("going to", url);
const iframe = document.createElement("iframe");
iframe.src = url;
iframe.hidden = true;
document.body.append(iframe);
await new Promise((res) => (iframe.contentWindow.onload = res));
l("starting observing price on", url);
2024-07-15 14:32:15 +03:00
const price = await observePriceOnPage(iframe.contentDocument.body, url);
document.body.removeChild(iframe);
return price;
2024-07-14 22:36:08 +03:00
} catch (e) {
l("getPriceForCountry", e, url);
return "";
}
};