Last active
October 22, 2020 11:58
-
-
Save bwindels/d0c00d5973a1987b3c19b0cfe474f290 to your computer and use it in GitHub Desktop.
Programatically download blob in new origin with one shared hidden iframe
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
| <!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> |
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
| <!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> |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This works on Safari on mac and iOS, Gnome Web, latest chrome and FF, IE11 but not pre-webkit edge.