Skip to content

Instantly share code, notes, and snippets.

@akira02
Last active December 28, 2023 08:40
Show Gist options
  • Save akira02/6e11cddf67a0d748bb7e19ece708c0c4 to your computer and use it in GitHub Desktop.
Save akira02/6e11cddf67a0d748bb7e19ece708c0c4 to your computer and use it in GitHub Desktop.
Batch add Melonbooks URLs to cart
async function addMelonCart() {
let list_text = prompt("Enter melonbooks url list (separated by newline)");
if (!list_text) return;
urlList = list_text.split("\n");
// filter empty url
urlList = urlList.filter((url) => url);
for (let i = 0; i < urlList.length; i++) {
const url = urlList[i];
// check if url is melonbooks
if (!url.includes("melonbooks.co.jp" && "product_id=")) {
console.warn(
`(${i + 1}/${urlList.length}) "${url}" is not a melonbooks url.`
);
continue;
}
let product_id = url.split("product_id=")[1];
if (!product_id) {
console.warn(
`(${i + 1}/${urlList.length}) "${url}" product_id not found.`
);
continue;
}
let title = "";
// Try to get transactionid from item page
await fetch(
`https://www.melonbooks.co.jp/detail/detail.php?product_id=${product_id}&adult_view=1`
)
.then((response) => response.text())
.then((html) => {
// Initialize the DOM parser
const parser = new DOMParser();
// Parse the text
const doc = parser.parseFromString(html, "text/html");
title = doc.getElementsByTagName("h1")[0].innerText;
const isInStock =
doc.getElementsByClassName("tag_cart_main2")?.length > 0;
if (!isInStock) throw new Error("Out of stock");
const transactionid = doc
.querySelector('#cart_anchor > input[name="transactionid"]')
.getAttribute("value");
if (!transactionid) throw new Error("Get transaction id failed");
return transactionid;
})
.then((transactionid) => {
fetch("https://www.melonbooks.co.jp/detail/detail.php?", {
headers: {
accept: "*/*",
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
},
body: `transactionid=${transactionid}&mode=cart_ajax&product_id=${product_id}&product_class_id=&favorite_product_id=&favorite_author_name=&quantity=1`,
method: "POST",
})
.then((response) => response.json())
.then((data) => {
console.log(
`(${i + 1}/${
urlList.length
}) Add to cart success: "${title}". Now in cart: ${
data?.quantity
}`
);
})
.catch(function (err) {
console.error(
`(${i + 1}/${urlList.length}) Add to cart failed: "${title}" `,
err
);
});
})
.catch(function (err) {
console.warn(
`(${i + 1}/${urlList.length}) Failed to fetch "${title}":`,
err.message
);
});
}
}
addMelonCart();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment