Dynamically created ahref click event not working

2019-07-15 12:50发布

问题:

i am creating ahref tag dynamically using javascript to download csv file generated using javascript code. The following code is working fine in chrome but doesn't work in safari or firefox...

var a = document.createElement('a');
var blob = new Blob([str], {'type':'application\/octet-stream'});
a.href = window.URL.createObjectURL(blob);
a.download = 'export.csv';
a.click();

any help is greatly appreciated..

回答1:

To make it work in Firefox, just insert the new element into the DOM (apendChild, etc).

I don't think this will work in Safari:

  • <a download=""> isn't (properly) supported yet, AFAIK. E.g. a.download = will not do what you want. You could still use setAttribute but Safari will still ignore it.
  • I don't think Safari does support downloading of blob:-URIs, anyway.