How to detect support for the HTML5 "download" attribute?
Asked Answered
K

2

46

One of the new features implemented in HTML5 is the download attribute for anchor tags. The benefit of this attribute is that it gives users the means to download content created within a client application, such as an image (converted from a canvas, for instance).

Currently, support for this feature is very poor, so I'd like to know how can I detect support for this feature in a browser.

Kimbra answered 24/8, 2012 at 16:0 Comment(1)
For anyone who's wondering, this feature is strongly supported as of 2022: caniuse.com/?search=download%20attribute%20aBengal
M
63

Use the Modernizr approach: create the element, and check if the attribute is defined:

var a = document.createElement('a');
if (typeof a.download != "undefined") {
    alert('has support');
}
Malvie answered 24/8, 2012 at 16:4 Comment(9)
Or the short version var downloadAttrSupported = ("download" in document.createElement("a"))Lemures
I suggested including Modernizr itself, but this might indeed be better if it's for one single usecase.Waiter
@AndreiOniga thanks for the suggestion, I updated my answer. Maybe (typeof a.download == 'string') would be safer still?Malvie
@dbaseman Actually, "undefined" is the standard implementation. Anything else isn't, to my knowledge, so checking whether "(typeof X == 'undefined')" or not is the way to go. Anyway, many thanks for the answer! It solved my problem :)Kimbra
This solution appears to not work anymore; modern versions of Firefox seem to have the a.download defined, but doesn't use it.Sewan
@Sewan which version are you referring to? I just checked Firefox 26, and it still shows a.download as undefined. Then again, this page claims that version 20 does have support, but but only for same-origin links: developer.mozilla.org/en-US/Firefox/Releases/…Malvie
@McGarnagle: using the console in Firefox 26 to do document.createElement('a').target returns an empty string on my Mac, not 'undefined'. I'm trying to download a data URL, so that probably doesn't fall under the "same-origin" umbrella...Sewan
@Sewan You do mean document.createElement('a').download, right? target should always return an empty string.Malvie
Whoops, right... document.createElement('a').download is an empty string too on Firefox 26 on my Mac!Sewan
S
1

A single-line if condition to keep things simplified:

if (document.createElement('a').download==undefined && e.target.hasAttribute('download'))
{
 e.preventDefault();
 console.log('Error: this is a download link, please right-click to save the file.');
}

Support for the download attribute is spotty (Chrome 14+, Firefox 20+, IE13+, Safari 10+ and no support in (real) Opera. The script above will not interfere with supported browsers.

Strahan answered 7/12, 2016 at 0:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.