Chrome 中表格的 CSV 导出不起作用 - JavaScript/AngularJS

CSV Export of Table in Chrome Not Working - JavaScript/AngularJS

本文关键字:不起作用 JavaScript AngularJS 表格 CSV Chrome      更新时间:2023-09-26

我目前正在修复 Web 应用程序上数据表的 CSV 导出。当您单击导出按钮时,它目前可以在除 Chrome 之外的所有需要的浏览器上导出。我一直在试图弄清楚它一段时间了,我拒绝拔掉我的头发。

下面的代码是我的服务,直到最近才工作。任何帮助将不胜感激。

svc.downloadContent =
(target, fileName, content) => {
  if (!browserSvc.canDownloadFiles()) return;
  // IE10
  if (window.navigator.msSaveOrOpenBlob) {
    const blob = new Blob([content], {type: 'text/csv'});
    window.navigator.msSaveOrOpenBlob(blob, fileName);
  // IE9
  } else if (env.browser === 'Explorer') {
    const frame = document.createElement('iframe');
    document.body.appendChild(frame);
    angular.element(frame).hide();
    const cw = frame.contentWindow;
    const cwDoc = cw.document;
    cwDoc.open('text/csv', 'replace');
    cwDoc.write(content);
    cwDoc.close();
    cw.focus();
    cwDoc.execCommand('SaveAs', true, fileName);
    document.body.removeChild(frame);
  // Sane browsers
  } else {
    const blob = new Blob([content], {type: 'text/csv'});
    const url = URL.createObjectURL(blob);
    const a = angular.element(target);
    const download = a.attr('download');
    // If not already downloading ...
    if (!download) {
      a.attr('download', fileName);
      a.attr('href', url);
      // This must run in the next tick to avoid
      // "$digest already in progress" error.
      //$timeout(() => target.click());
      try {
        target.click();
        // Clear attributes to prepare for next download.
        a.attr('download', '');
        a.attr('href', '');
      } catch (e) {
        console.error('csv-svc.js: e =', e);
      }
    }
  }

我在发布问题几分钟后就设法弄清楚了这一点。如果只是为了 Chrome,我需要添加一个 else。但是,我将发布修复程序并将其保留,希望将来可以帮助其他人。

else if (env.browser === 'Chrome') {
    const blob = new Blob([content], {type: 'text/csv'});
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.style = 'visibility:hidden';
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }