Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IE9 - no way to save the results of CSV export #2312

Closed
alexandery opened this issue Dec 9, 2014 · 16 comments
Closed

IE9 - no way to save the results of CSV export #2312

alexandery opened this issue Dec 9, 2014 · 16 comments
Assignees
Milestone

Comments

@alexandery
Copy link

Clicking the link that gets generated by the grid results in navigation to an empty page in IE9 - no way to save the file even from the context menu "Save Target As...". Firefox prompts you to save the file.

@PaulL1
Copy link
Contributor

PaulL1 commented Dec 10, 2014

Unfortunately I don't have an IE install to diagnose on. Does it give you any errors or information as to why it's not working?

@PaulL1 PaulL1 added this to the 3.0 milestone Dec 10, 2014
@alexandery
Copy link
Author

Paul,

There is no error. It does generate the link as expected, but the link does not allow the content to be downloaded in IE. Clicking on it just redirects browser to an empty page.

I did look around and found this article: http://andrew-b.com/view/article/44 , with the code that gives you an idea as to how to go about CSV saving with IE:

//Save file
if (navigator.appName == "Microsoft Internet Explorer") {

    //Optional: If you run into delimiter issues (where the commas are not interpreted and all data is one cell), then use this line to manually specify the delimeter

     tableString = 'sep=,\r\n' + tableString;

     myFrame.document.open("text/html", "replace");
     myFrame.document.write(tableString);
     myFrame.document.close();
     myFrame.focus();
     myFrame.document.execCommand('SaveAs', true, 'data.csv');
 } else {

    csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(tableString);
     $(event.target).attr({
         'href': csvData,
         'target': '_blank',
         'download': 'my_data.csv'
     });

 }

And then there are posts like this: http://stackoverflow.com/a/24505999 which talk about Opera issues.

Hope this helps. Let me know if you need any other information.

Thanks!

@alexandery alexandery changed the title IE9 - no way to save the restuls of CSV export IE9 - no way to save the resutls of CSV export Dec 10, 2014
@alexandery alexandery changed the title IE9 - no way to save the resutls of CSV export IE9 - no way to save the results of CSV export Dec 10, 2014
@PaulL1
Copy link
Contributor

PaulL1 commented Dec 26, 2014

I have recently updated the csv download to avoid the link click entirely. I think the code I used was IE aware as well. Could you review and see if this is still occurring?

@alexandery
Copy link
Author

@PaulL1,

Thanks for the update. I've tried the latest unstable version today (v3.0.0-RC.18-f8a68cc). Unfortunately the export functionality doesn't seem to work for IE9 still. Upon exporting IE9 pops up a new, completely empty window.

The code generates CSV data, but when it gets to 'downloadFile' method, the execution gets to lines 14081-14082 and continues from there.

Would appreciate any pointers or suggestions on how to go about testing and figuring out what's wrong there.

Thanks!

@PaulL1
Copy link
Contributor

PaulL1 commented Jan 14, 2015

@alexandery: what is at lines 14081-14082? I did some changes on downloadFile a few days ago, but I doubt they fixed it. If you can tell me what line it is in that the error occurs, I can have a look.

@alexandery
Copy link
Author

@PaulL1 Well, I thought you could check the file to get the content of the lines. However, I have implemented the feature myself. I hope you can integrate this into the component to make sure that others can use it (and that I won't need to apply these changes next time I upgrade).

Below is the code to implement it on IE9 (possibly below as well). All of it goes into ui.grid.exporter.

  • New method to check for IE version
        /**
         * @ngdoc function
         * @name isIE
         * @methodOf  ui.grid.exporter.service:uiGridExporterService
         * @description Checks whether current browser is IE and returns it's version if it is
        */
        isIE: function () {
            var myNav = navigator.userAgent.toLowerCase();
            return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
        }
  • Modified downloadFile() method
downloadFile: function (fileName, csvContent) {
  var D = document;
  var a = D.createElement('a');
  var strMimeType = 'application/octet-stream;charset=utf-8';
  var rawFile;

  if (!fileName) {
    var currentDate = new Date();
    fileName = "CWS Export - " + currentDate.getFullYear() + (currentDate.getMonth() + 1) +
                  currentDate.getDate() + currentDate.getHours() +
                  currentDate.getMinutes() + currentDate.getSeconds() + ".csv";
  }

  if (this.isIE() < 10) {
    var frame = D.createElement('iframe');
    document.body.appendChild(frame);

    frame.contentWindow.document.open("text/html", "replace");
    frame.contentWindow.document.write('sep=,\r\n' + csvContent);
    frame.contentWindow.document.close();
    frame.contentWindow.focus();
    frame.contentWindow.document.execCommand('SaveAs', true, fileName);

    document.body.removeChild(frame);
    return true;
  }

  // IE10+
  if (navigator.msSaveBlob) {
    return navigator.msSaveBlob(new Blob(["\ufeff", csvContent], {
      type: strMimeType
    }), fileName);
  }

  //html5 A[download]
  if ('download' in a) {
    var blob = new Blob([csvContent], {
      type: strMimeType
    });
    rawFile = URL.createObjectURL(blob);
    a.setAttribute('download', fileName);
  } else {
    rawFile = 'data:' + strMimeType + ',' + encodeURIComponent(csvContent);
    a.setAttribute('target', '_blank');
    a.setAttribute('download', fileName);
  }


  a.href = rawFile;
  a.setAttribute('style', 'display:none;');
  D.body.appendChild(a);
  setTimeout(function() {
    if (a.click) {
      a.click();
      // Workaround for Safari 5
    } else if (document.createEvent) {
      var eventObj = document.createEvent('MouseEvents');
      eventObj.initEvent('click', true, true);
      a.dispatchEvent(eventObj);
    }
    D.body.removeChild(a);

  }, 100);
}
  • Need to make sure that the following CSS is applied because it seems that adding and removing an iFrame changes browser width a little which triggers a bug in ui-grid - ui-grid-viewport gets pushed below by the row header checkmarks:
.ui-grid-viewport {
     width: auto !important;
}

@alexandery
Copy link
Author

@PaulL1 Have you seen this yet? There is no reply from you.

@PaulL1 PaulL1 self-assigned this Feb 6, 2015
@PaulL1
Copy link
Contributor

PaulL1 commented Feb 28, 2015

@alexandery : I have applied the changes as you provided. However, I cannot test (I don't have any IE), and I couldn't apply the css change as that breaks the all features tutorial. Is there an alternative to that change that doesn't have an impact on other browsers?

@PaulL1
Copy link
Contributor

PaulL1 commented Feb 28, 2015

Closed via 073c2a5

@PaulL1 PaulL1 closed this as completed Feb 28, 2015
@tanak
Copy link
Contributor

tanak commented Mar 2, 2015

Hi.
I became unable to export a csv file with the latest version in Chrome.

I think the problem could be here.

if (this.isIE() < 10) {

isIE() returns false when using browsers other than Internet Explorer, but because
false < 10 returns true, so it works as if using IE.

@alexandery
Copy link
Author

@tanak, @PaulL1 : my bad. I forgot to update the post here with the code - that issue was fixed right away, but slipped through my fingers here. Here is the code that should have been here. Sorry about the confusion that led to this bug.

        /**
         * @ngdoc function
         * @name isIEBelow10
         * @methodOf  ui.grid.exporter.service:uiGridExporterService
         * @description Checks whether current browser is IE and of version below 10
        */
        isIEBelow10: function () {
            var myNav = navigator.userAgent.toLowerCase();
            return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) < 10 : false;
        },

        /**
         * @ngdoc function
         * @name downloadFile
         * @methodOf  ui.grid.exporter.service:uiGridExporterService
         * @description Triggers download of a csv file.  Logic provided
         * by @cssensei (from his colleagues at https://github.com/ifeelgoods) in issue #2391
         * @param {string} fileName the filename we'd like our file to be
         * given
         * @param {string} csvContent the csv content that we'd like to 
         * download as a file
         */
        downloadFile: function (fileName, csvContent) {
          var D = document;
          var a = D.createElement('a');
          var strMimeType = 'application/octet-stream;charset=utf-8';
          var rawFile;

          if (!fileName) {
            var currentDate = new Date();
            fileName = "CSV Export - " + currentDate.getFullYear() + (currentDate.getMonth() + 1) +
                          currentDate.getDate() + currentDate.getHours() +
                          currentDate.getMinutes() + currentDate.getSeconds() + ".csv";
          }

          if (this.isIEBelow10()) {
            var frame = D.createElement('iframe');
            document.body.appendChild(frame);

            frame.contentWindow.document.open("text/html", "replace");
            frame.contentWindow.document.write('sep=,\r\n' + csvContent);
            frame.contentWindow.document.close();
            frame.contentWindow.focus();
            frame.contentWindow.document.execCommand('SaveAs', true, fileName);

            document.body.removeChild(frame);
            return true;
          }

          // IE10+
          if (navigator.msSaveBlob) {
            return navigator.msSaveBlob(new Blob(["\ufeff", csvContent], {
              type: strMimeType
            }), fileName);
          }

          //html5 A[download]
          if ('download' in a) {
            var blob = new Blob([csvContent], {
              type: strMimeType
            });
            rawFile = URL.createObjectURL(blob);
            a.setAttribute('download', fileName);
          } else {
            rawFile = 'data:' + strMimeType + ',' + encodeURIComponent(csvContent);
            a.setAttribute('target', '_blank');
            a.setAttribute('download', fileName);
          }


          a.href = rawFile;
          a.setAttribute('style', 'display:none;');
          D.body.appendChild(a);
          setTimeout(function() {
            if (a.click) {
              a.click();
              // Workaround for Safari 5
            } else if (document.createEvent) {
              var eventObj = document.createEvent('MouseEvents');
              eventObj.initEvent('click', true, true);
              a.dispatchEvent(eventObj);
            }
            D.body.removeChild(a);

          }, 100);
        }

Hope this helps.

@tanak
Copy link
Contributor

tanak commented Mar 2, 2015

@alexandery, thank you for your code.
I think your code is easier to understand, so it could be better to send your pull request.
How do you think, @PaulL1 ?

@kellywatson
Copy link

Hi ,
In safari (version 5.1.7) file name and type is "unknown". Is there any alternative to get the file name in safari.

Thanks!

@reddysainathn
Copy link

Thank you for the hint,
When I use custom fileName,it is not able to take it.When I replace fileName with "filename.txt",anything in quotes gives the name.
frame.contentWindow.document.execCommand('SaveAs', true, fileName);

Is there a fix for this,that I am missing?

@nileshnaseet
Copy link

nileshnaseet commented May 9, 2016

@alexandery awesome solution for < IE10. Is there anyway we can get 'Save' or 'Cancel' return for "SaveAs" command? To check if user has clicked Save or Cancel.

@nileshnaseet
Copy link

got it...returns TRUE if user click 'Save' and FALSE if 'Cancel'.

Thanks anyway..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

6 participants