[英]dispatchEvent doesn't work in javascript with Internet explorer 11
在我的网站上,我有一个 javascript,我希望在其中打开一个文件保存对话框。 目的是将一些来自 web 服务器的数据保存在文本文件中。
我正在尝试使用这篇文章中显示的代码片段:
准确地说:
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
if (document.createEvent) {
var event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
pom.dispatchEvent(event);
}
else {
pom.click();
}
}
这适用于 Firefox 和 Chrome。 但是,对于 Internet Explorer 11,它不起作用。 当这条指令被执行...
pom.dispatchEvent(event);
...什么都没发生。 保存对话框没有打开,浏览器java控制台也没有报错。 事件似乎迷失在虚空中。 任何帮助将不胜感激。
这在现代浏览器中得到广泛支持。 然而,
旧版本的 IE 支持等效的专有 EventTarget.fireEvent() 方法。
来源: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent
您的代码在 Internet Explorer 11.836.18362.0 中对我来说可以正常工作,但是话虽如此,MDN 建议不要使用您正在使用的技术。 createEvent
和initEvent
已被贬低,可能会产生不可预知的结果,并且可能随时被删除。 请改用Event()
。 请参阅initEvent
和createEvent
MDN 文档页面。
我试图测试我这边的问题,我可以看到该文件没有在 IE 11 浏览器中下载。
以下是可用于 IE 和其他浏览器的修改后的代码。 它将正确下载文件。
<!doctype html>
<html>
<head>
<script>
function download(data, filename, type)
{
var file = new Blob([data], {type: type});
if (window.navigator.msSaveOrOpenBlob)
{
window.navigator.msSaveOrOpenBlob(file, filename);
}
else
{ var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(data));
pom.setAttribute('download', filename);
if (document.createEvent)
{
var event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
pom.dispatchEvent(event);
}
else
{
pom.click();
}
}
}
download('Hello world!','test.txt','text/plain');
</script>
</head>
<body>
<h2>Refresh the page</h2>
</body>
</html>
IE 11 浏览器中的 Output:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.