Skip to content

Instantly share code, notes, and snippets.

@willmendesneto
Last active April 9, 2021 04:46
Show Gist options
  • Save willmendesneto/9b5de52068892dee6ac5804aca7e0db6 to your computer and use it in GitHub Desktop.
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
/**
* 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