【问题标题】:dispatchEvent doesn't work in javascript with Internet explorer 11dispatchEvent 在 Internet Explorer 11 的 javascript 中不起作用
【发布时间】:2020-05-28 14:25:17
【问题描述】:

在我的网站中,我有一个 javascript,我希望在其中打开一个文件保存对话框。目的是将一些来自网络服务器的数据保存在一个文本文件中。

我正在尝试使用本文中显示的代码 sn-p:

[Using HTML5/JavaScript to generate and save a file

准确地说:

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控制台也没有报错。事件似乎迷失在虚空中。 任何帮助将不胜感激。

【问题讨论】:

    标签: javascript modal-dialog internet-explorer-11 dispatchevent


    【解决方案1】:

    这在现代浏览器中得到广泛支持。然而,

    旧版本的 IE 支持等效的专有 EventTarget.fireEvent() 方法。

    来源:https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent

    【讨论】:

      【解决方案2】:

      您的代码在 Internet Explorer 11.836.18362.0 中运行良好, 但是话虽如此,MDN 建议不要使用您正在使用的技术。 createEventinitEvent 已被弃用,可能会产生不可预知的结果,并且可能随时被删除。请改用Event()。请参阅 initEventcreateEvent MDN 文档页面。

      【讨论】:

        【解决方案3】:

        我尝试测试我这边的问题,我可以看到该文件没有在 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 浏览器中的输出:

        【讨论】:

          猜你喜欢
          • 2016-10-20
          • 2019-08-12
          • 2014-08-22
          • 1970-01-01
          • 1970-01-01
          • 2015-03-22
          • 2018-01-17
          • 2017-04-02
          • 1970-01-01
          相关资源
          最近更新 更多