Last active
April 13, 2024 23:36
-
-
Save keikoro/699e2003d5814bc0d5224a9e78676373 to your computer and use it in GitHub Desktop.
JavaScript bookmarklet for converting HTML-formatted Firefox bookmarks into a downloadable CSV file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
javascript:(function(){ | |
/* escape quotes and commas in contents to be comma-separated */ | |
function wrapCsvContents(content) { | |
if (typeof(content) === 'string') { | |
if (content.replace(/ /g, '').match(/[\s,"]/)) { | |
return '"' + content.replace(/"/g, '""') + '"'; | |
} | |
} | |
return content; | |
} | |
/* filter bookmarks */ | |
let nodeList = window.document.querySelectorAll('dt a'); | |
let contents = Array.from(nodeList); | |
let bookmarks = contents.filter(function(a) { | |
let h = a.getAttribute('href'); | |
if (h && !h.startsWith('place')) { | |
return true; | |
} | |
}); | |
/* extract basic info from FF bookmarks - name, url, date added - and sort them by name ASC */ | |
let output = bookmarks.map(function(a) { | |
let obj = {}; | |
obj.name = a.innerHTML; | |
obj.url = a.getAttribute('href'); | |
let date = new Date(parseInt(a.getAttribute('add_date')) * 1000); | |
obj.added = date.toISOString(); | |
return obj; | |
}).sort((a, b) => a.name.localeCompare(b.name)); | |
/* pour the bookmark contents into CSV format */ | |
let csvContent = 'name,url,date added\r\n'; | |
output.forEach(function(obj) { | |
let row = [wrapCsvContents(obj.name), wrapCsvContents(obj.url), obj.added].join(','); | |
csvContent += row + '\r\n'; | |
}); | |
/* put CSV contents into a CSV file reusing the original HTML file's date */ | |
let file = new Blob([csvContent], {type: 'text/csv;charset=utf-8;'}); | |
let getFileDate = new Date(window.document.lastModified).toISOString().slice(0, 10); | |
let downloadLink = window.document.createElement('a'); | |
downloadLink.setAttribute('href', window.URL.createObjectURL(file)); | |
downloadLink.setAttribute('download', 'bookmarks-' + getFileDate + '.csv'); | |
downloadLink.innerHTML = 'Download CSV'; | |
/* make resulting .csv downloadable via link in the HTML file */ | |
let firstElem = window.document.body.firstChild; | |
window.document.body.insertBefore(downloadLink, firstElem); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment