1

I'm trying to dynamically set the value for the download attribute of an anchor. This should be the file name of the downloaded file. However, the filename is defaulting to its original value, not the value I'm trying to give it.

EDIT: It was pointed out that the download attribute value IS actually getting changed in the DOM. However, the filename of the file downloaded is not properly assigned.

EDIT: Does not seem to be a problem with dynamically set value. Even hard-coded, the filename is not getting set.

<a href="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" download="image.png">click</a>

http://jsfiddle.net/abalter/2wz5zs7r/

HTML:

<button>Set url and download name for anchor</button>
<a href="" download="">Download Google logo</a>

Javascript:

var googleLogoURL = "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"; 
$('button').on('click', function(){
    alert("url and filename set");
    $('a').prop({
        'href': googleLogoURL,
        'download': "google-logo.png"
    });
});
abalter
  • 9,663
  • 17
  • 90
  • 145
  • 1
    It does set. If you open developer tools, you will see that it became `Download Google Logo`. – Yeldar Kurmangaliyev Nov 13 '15 at 06:55
  • @YeldarKurmangaliyev Good observation. The problem IS that when you click the download link, the filename of the file that gets downloaded is wrong -- not changed. I'm editing my post to clarify that point. – abalter Nov 13 '15 at 07:06
  • Any reason not to use `window.location.href` ? http://stackoverflow.com/questions/1296085/download-file-using-jquery – Twisty Nov 13 '15 at 07:16
  • That doesn't allow me to set the filename of the downloaded file. Besides, the new HTML5 attribute should be the "new" way to do this. – abalter Nov 13 '15 at 07:19
  • Tested in FireFox with Firebug and I can see the DOM 'download' for that `a` update to `"google-logo.png"`. It still attempts to save as the wrong name. So not sure where the browser is pulling that info. – Twisty Nov 13 '15 at 07:22
  • What about replacing it? http://jsfiddle.net/Twisty/2wz5zs7r/2/ – Twisty Nov 13 '15 at 07:39
  • All that happens when I click the button is that the link goes away. – abalter Nov 13 '15 at 16:58

1 Answers1

2

It doesn't work because the webpage you are running the JS in is, presumably, not hosted on https://www.google.com.

From the HTML 5 spec:

In cross-origin situations, the download attribute has to be combined with the Content-Disposition HTTP header, specifically with the attachment disposition type, to avoid the user being warned of possibly nefarious activity. (This is to protect users from being made to download sensitive personal or confidential information without their full understanding.)

From MDN:

This attribute is only honored for links to resources with the same-origin.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335