Skip to content

Instantly share code, notes, and snippets.

@quanon
Last active May 15, 2022 11:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quanon/e6894e891ffba08d8df6b07352f9706f to your computer and use it in GitHub Desktop.
Save quanon/e6894e891ffba08d8df6b07352f9706f to your computer and use it in GitHub Desktop.
MTG Mint Card の購入履歴を CSV でダウンロードする
const convertTableToRows = (selector) => {
const table = document.querySelector(selector);
const rows = [];
const headers = Array.from(table.querySelectorAll('tr:first-child th')).map(th => th.innerText);
rows.push(headers);
table.querySelectorAll('tr').forEach(tr => {
const row = [];
tr.querySelectorAll('td').forEach(td => {
row.push(td.innerText);
if (td.colSpan && td.colSpan > 1) {
row.push(...new Array(td.colSpan - 1).fill(''));
}
});
rows.push(row);
});
return rows;
};
const convertRowsToCSV = rows => {
return rows.map(row => row.map(value => `"${value}"`)).join("\n");
};
const getOrderDate = () => {
// Get dd element next to td element of Order Date.
const xpath = "//dt[text()='Order Date']/following-sibling::dd[1]";
const dd = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
const orderDate = new Date(dd.innerText);
return orderDate;
};
const downloadCSV = (csv, filename) => {
const csvFile = new Blob([csv], { type: 'text/csv' });
const tempLink = document.createElement('a');
const orderDate = getOrderDate();
tempLink.style.display = 'none';
tempLink.download = filename;
tempLink.href = URL.createObjectURL(csvFile);
document.body.appendChild(tempLink);
tempLink.click();
document.body.removeChild(tempLink);
return filename;
};
const rows = convertTableToRows('table');
const csv = convertRowsToCSV(rows);
const tempLink = document.createElement('a');
const orderDate = getOrderDate();
downloadCSV(csv, `${orderDate.toISOString()}.csv`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment