Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect support for the HTML5 "download" attribute?

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.

like image 680
Andrei Oniga Avatar asked Aug 24 '12 16:08

Andrei Oniga


People also ask

How do I know my browser support HTML5?

The getContext method is checked by accessing it on the created input object. The result of this expression is checked with an if-statement. If the result is true, it means that HTML5 is supported by the browser.

Why download attribute is not working in HTML?

The download attribute only works for same-originl URLs. So if the href is not the same origin as the site, it won't work. In other words, you can only download files that belongs to that website. This attribute follows the same rules outline in the same-origin policy.

How does HTML download attribute work?

The download attribute specifies that the target (the file specified in the href attribute) will be downloaded when a user clicks on the hyperlink. The optional value of the download attribute will be the new name of the file after it is downloaded.


2 Answers

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'); } 
like image 119
McGarnagle Avatar answered Sep 25 '22 14:09

McGarnagle


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.

like image 27
John Avatar answered Sep 26 '22 14:09

John