Skip to content

Instantly share code, notes, and snippets.

@bwindels
Last active October 22, 2020 11:58
Show Gist options
  • Select an option

  • Save bwindels/d0c00d5973a1987b3c19b0cfe474f290 to your computer and use it in GitHub Desktop.

Select an option

Save bwindels/d0c00d5973a1987b3c19b0cfe474f290 to your computer and use it in GitHub Desktop.
Programatically download blob in new origin with one shared hidden iframe
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<p><a id="link" href="#">Download!</a></p>
<script type="text/javascript">
var link = document.getElementById("link");
function download(blob, filename) {
if (navigator.msSaveBlob) {
navigator.msSaveBlob(blob, filename);
} else {
var url = URL.createObjectURL(blob);
link.href = url;
link.download = filename;
link.click();
}
}
window.addEventListener("message", function(event) {
if (event.data.type === "download") {
download(event.data.blob, event.data.filename);
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
iframe {
display: none;
}
</style>
</head>
<body>
<iframe id="download-handler" src="download-handler-sandbox.html" sandbox="allow-scripts allow-downloads allow-downloads-without-user-activation"></iframe>
<p><a href="#" id="download-hello">Download hello.txt</a> <a href="#" id="download-lorem">Download lorem.txt</a></p>
<script type="text/javascript">
const downloadHandler = document.getElementById("download-handler");
function downloadBlob(blob, filename) {
downloadHandler.contentWindow.postMessage({type: "download", blob: blob, filename: filename}, "*");
}
document.getElementById("download-hello").addEventListener("click", function(event) {
event.preventDefault();
var blob = new Blob(["hello world"], {type: "text/plain"});
downloadBlob(blob, "hello.txt");
});
document.getElementById("download-lorem").addEventListener("click", function(event) {
event.preventDefault();
var blob = new Blob(["Lorem ipsum dolor sit amet, consectetur adipiscing elit."], {type: "text/plain"});
downloadBlob(blob, "lorem.txt");
});
</script>
</body>
</html>
@bwindels
Copy link
Author

This works on Safari on mac and iOS, Gnome Web, latest chrome and FF, IE11 but not pre-webkit edge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment