2

The following HTML file when opened in chrome, downloads the test.gif file. On firefox/IE, nothing happens.

<html>
<head>
<script type="text/JavaScript" language="JavaScript">
    function s() {
       var link = document.createElement('a');
       link.download = "test.gif";
       link.href = 'http://192.168.20.22/mantis/images/mantis_logo.gif';
       link.click();
    }
</script>
</head>
<body onload="s()" >
</body>
</html>

Firebug tells me that the link object is properly created and href is set, but somehow on calling link.click() nothing happens. Any idea why?

  • Check link http://stackoverflow.com/questions/29494715/jquery-file-download-works-in-chrome-but-not-firefox. It may help you to solve the issue. – Pramod Oct 20 '15 at 12:21
  • 1
    You need to add the link to the body. This is what you need: http://stackoverflow.com/questions/3665115/create-a-file-in-memory-for-user-to-download-not-through-server/20194533#20194533 – Eirik H Oct 20 '15 at 12:23
  • also check this question: http://stackoverflow.com/questions/809057/how-do-i-programmatically-click-on-an-element-in-firefox many answers there will give you hints on how to proceed – valepu Oct 20 '15 at 12:26

1 Answers1

2

I think it needs to be added to the DOM before it will work. Try this:

function s() {
   var link = document.createElement('a');
   link.download = "test.gif";
   link.href = 'http://192.168.20.22/mantis/images/mantis_logo.gif';
   document.body.appendChild(link);
   link.click();
}

And if you don't want it hanging around you can immediately remove it as well by adding this after the click:

link.parentNode.removeChild(link);
AtheistP3ace
  • 9,611
  • 12
  • 43
  • 43