Skip to content

Instantly share code, notes, and snippets.

@sourcec0de
Last active August 30, 2018 15:12
Show Gist options
  • Save sourcec0de/4d16be547c60a7188739 to your computer and use it in GitHub Desktop.
Save sourcec0de/4d16be547c60a7188739 to your computer and use it in GitHub Desktop.
Initiating downloads in javascript

Downloads in javascript

Method 1

Use this method when viewing images or textual data. It allows you to open it in a seperate window. This will cause a popup blocker to react.

window.open(url,'_blank');

Method 2

Use this method when the Content-Disposition header is set to attachement. This will not change the url of the current window but will start the native browser download dialog.

window.location = url;

Method 3

This method is a middle ground between the two above, but it will only start a download. If you have the need for the browser to render an image in a new window then one of the methods above.

window.open(url,'_self');

Final Notes

My prefered way of doing this is to find a way to determine the Content-Type and based on that use the first or second under certain circumstances.

  • if Content-Type: image / text
    • use method 1
  • if Content-Disposition: attachement or Content-Type: zip / gz / other / etc...
    • use method 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment