Chrome 中 Table 的 CSV 导出无效 - JavaScript/AngularJS

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

我目前正在修复 Web 应用程序上的数据 table 的 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);
      }
    }
  }

我在 post 回答我的问题几分钟后就设法解决了这个问题。如果只是为了 Chrome,我需要添加一个 else。但是,我会 post 修复并保留它,希望它能在将来帮助其他人。

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);

  }