-
Notifications
You must be signed in to change notification settings - Fork 0
/
content.js
42 lines (37 loc) · 1.33 KB
/
content.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.action === "getTables") {
const tables = Array.from(document.querySelectorAll("table.wikitable"))
sendResponse({ tables: tables.map((table) => table.outerHTML) })
} else if (request.action === "downloadTable") {
const tables = Array.from(document.querySelectorAll("table.wikitable"))
const tableIndex = request.tableIndex
if (tableIndex >= 0 && tableIndex < tables.length) {
const csvContent = convertTableToCSV(tables[tableIndex])
downloadCSV(csvContent, "table_" + (tableIndex + 1) + ".csv")
}
}
})
function convertTableToCSV(table) {
const rows = Array.from(table.querySelectorAll("tr"))
const csvData = []
rows.forEach((row) => {
const rowData = []
Array.from(row.children).forEach((cell) => {
const cellText = cell.textContent.trim().replace(/\s\s+/g, " ")
rowData.push(cellText)
})
csvData.push(rowData.join(","))
})
return csvData.join("\n")
}
function downloadCSV(content, filename) {
const blob = new Blob([content], { type: "text/csv" })
const url = window.URL.createObjectURL(blob)
const a = document.createElement("a")
a.href = url
a.download = filename
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
window.URL.revokeObjectURL(url)
}