Last active
October 20, 2020 19:44
-
-
Save dotspencer/ee931c53a893111440bb256c85af12e2 to your computer and use it in GitHub Desktop.
Simplest way to generate and download a file using Javascript
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
function download(filename, text){ | |
// MIME types: https://www.freeformatter.com/mime-types-list.html#mime-types-list | |
var blob = new Blob([text], {type: "text/plain"}); | |
var url = window.URL.createObjectURL(blob); | |
var a = document.createElement("a"); | |
a.href = url; | |
a.download = filename; | |
a.click(); | |
} | |
download("text.txt", "file contents here..."); |
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
var saved = {}; | |
setInterval(() => savePages(), 200); | |
async function savePages() { | |
const srcs = Array.from(document.querySelectorAll('img[src^="https://books.google.com/books/content"][style]')).map(el => el.src); | |
for (let i = 0; i < srcs.length; i++) { | |
const src = srcs[i]; | |
const page = getParam(src, 'pg'); | |
if (!saved[page]) { | |
saved[page] = true; | |
const blob = await fetch(src).then(res => res.blob()); | |
download(blob, page + '.png'); | |
} | |
} | |
} | |
function getParam(url, param){ | |
url = new URL(url); | |
return new URLSearchParams(url.search).get(param); | |
} | |
function download(blob, filename) { | |
var url = window.URL.createObjectURL(blob); | |
var a = document.createElement("a"); | |
a.href = url; | |
a.download = filename; | |
a.click(); | |
} |
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
(async () => { | |
// https://utah.pbslearningmedia.org/resource/ae339529-1ab8-4cb2-bdbe-75b94287d6c9/us-states-shapes-and-names-clipart/ | |
const state = document.querySelector('.item-description').innerText.match(/state of (.+) as/)[1]; | |
const img = document.querySelector('.row.gallery-item-wrapper .poster-image'); | |
const url = img.src.split('.resize')[0]; | |
const blob = await fetch(url).then(res => res.blob()); | |
download(blob, state + '.png'); | |
function download(blob, filename) { | |
var url = window.URL.createObjectURL(blob); | |
var a = document.createElement("a"); | |
a.href = url; | |
a.download = filename; | |
a.click(); | |
} | |
document.querySelector('.preview-button.preview-right').click() | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment