0

In my page I have a download button that download the screen content in a CSV file.

The CSV file is generated by another function in Javascript based on my grid data.

The code I´m using to generate data is based on that post.

All is fine, except that I don´t want to have an tag on my screen, but a styled button. I can´t have a form on that place neither. Just a plain button.

So, I have to create the on the fly, fire it and then delete it.

Here is my code:

<button type='button' onclick='buttonClicked(); return false;' class='btn btn-primary btn-xs'>Export</button>

Now my function:

var buttonClicked = function () {

    var content = getMyCsvData(); /// custom function to get CSV data

    if (window.navigator.msSaveOrOpenBlob) {
        alert('blob');
        var fileData = [content];
        blobObject = new Blob(fileData);
        window.navigator.msSaveOrOpenBlob(blobObject, "download_data");
    } else {
        var tempRef = $("<a download='' href='#'>download</a>");
        var url = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
        $(tempRef).attr("href", url);
        this.element.append(tempRef);
        $(tempRef).click();
        this.element.remove(tempRef);
    }

This code sounds strange for me and it´s not working for Chrome (that uses the href approach for downloading data).

So, quetions:

  1. Is there a better way of attaching the event to the button without creating the ?

  2. If not, how can I create my anchor, fire my temporary anchor and then delete it without affecting my current screen ?

Thanks for help.

Community
  • 1
  • 1
Mendes
  • 17,489
  • 35
  • 150
  • 263

1 Answers1

0

You can use window.location to navigate to a URL, including data:

window.location = 'data:....';

See an example at http://jsfiddle.net/KngFC/

However, this will not trigger a download when the type can be displayed in-browser, it will instead replace your application with the download unless the type cannot be displayed within the browser. You can trigger a new window/tab, which is probably what you want:

window.open('data:....', '_blank');

This will cause a new tab to open, the download will start, and once accepted or declined, and if the data can't be shown in the browser the tab will be closed.

See a working example (with CSV) at http://jsfiddle.net/EHV6m/

A common approach attempted by new developers (that does not work) is to attempt to trigger a click on the element using jQuery's .click(). However, while calling click() without arguments will trigger jQuery-registered Javascript events, it does not trigger the built-in browser actions.

Here is an example of this approach (this does not work): http://jsfiddle.net/t5uvP/1/

William Lahti
  • 1,150
  • 11
  • 11