Last active
April 9, 2021 04:46
-
-
Save willmendesneto/9b5de52068892dee6ac5804aca7e0db6 to your computer and use it in GitHub Desktop.
Dowload file sync. Alternative option for `window.open`, but running download file in sync
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
/** | |
* Usage | |
* downloadFileSync('file-url', {name: 'filename', iframeName: 'my-amazing-iframe-name' }) | |
*/ | |
const downloadFileSync = ( | |
url: string, | |
filename?: string; | |
) => { | |
const iframeName = options?.iframeName ?? 'reusable-iframe'; | |
const link = document.createElement('a'); | |
let iframe: HTMLIFrameElement | null = document.querySelector(`#${iframeName}`); | |
if (!iframe) { | |
iframe = document.createElement('iframe'); | |
iframe.style.display = 'none'; | |
iframe.id = iframeName; | |
iframe.name = iframeName; | |
document.body.append(iframe); | |
} | |
link.href = url; | |
if (filename) { | |
link.download = filename; | |
} | |
link.target = iframeName; | |
document.body.append(link); | |
link.click(); | |
link.remove(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment