[英]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.