Last active
August 3, 2020 13:18
-
-
Save kthwaite/5934d0b2253cce2b65dfbd39e3186dab to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* Extract and data from the DOM in JSON format. | |
* @param selector {string} - Selector to query. | |
* @param extractor {function} - Operation to apply to each DOM element. | |
* @param filename {string} | |
*/ | |
function selectorToJson(selector, extractor, filename) { | |
const elements = document.querySelectorAll(selector); | |
const data = Array.from(elements).map(extractor); | |
if(filename == null) { | |
return data; | |
} | |
const blob = new Blob([JSON.stringify(data)], {type: 'text/json'}); | |
const a = document.createElement('a'); | |
a.download = filename; | |
a.href = window.URL.createObjectURL(blob); | |
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':'); | |
const evt = new MouseEvent('click'); | |
a.dispatchEvent(evt); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment