click() works fine in Chrome but not in IE11

2019-09-15 02:22发布

问题:

I'm testing the following piece of Javascript code on the Console before I include it into my application (I found it on SO)

pom = document.createElement('a')
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent("Hello World!"))
pom.setAttribute('download', "IEpomTest")
pom.style.display = 'none'
document.body.appendChild(pom)
pom.click()
document.body.removeChild(pom)

This is working fine on Chrome and the pom.click() downloads a text file with "Hello World!" in it, but when I try it on IE11, the "pom.click()" takes me to this URL "data:text/plain;charset=utf-8,Hello%20World!" and I get the error message "The webpage cannot be displayed".

Anyone has an idea what am I doing wrong?

回答1:

IE will try to open as a website, a better approach might be checking if window.navigator.msSaveBlob is present, and if is, Using this method to download the file