2

I need to trigger a CSV download, but window.open() is failing in this context. No console error.

I'm calling exportRecords() in Customer.vue, which delegates the handling logic to services.js via customer_actions.js. At this point, I assume the scope of window is the issue.

If I move window.open() outside of this.exportCsv(), it works -- although I have no data.

Customer.vue

<button @click.prevent="exportRecords">Export</button>

<script>
import * as actions from '../../vuex/customers_actions';

export default {
  vuex: {
    actions
  },

  data () {
    return {
      grid: {}
    };
  },

  methods: {
    exportRecords: function () {
      this.exportCsv([this.$data.grid], function (response) {
        window.open('data:text/csv;charset=utf-8,' + encodeURIComponent(response));
      });
    }
  }
};
</script>

customers_actions.js

import { ApiService } from './services';

export const exportCsv = function (store, grids = [], successCallback) {
  ApiService(
    store,
    {
      noun: 'Customer',
      verb: 'GetRecordsViewDataAsCSVFile',
      data: {}
    },
    successCallback,
    'csv'
  );
};

services.js

export const ApiService = (store, options, successCallback, responseType = 'json') => {
  let parameters = {};

  store.dispatch('SET_BUSY');

  Vue.http.post(API_URL, parameters, []).then((promise) => {
    return promise.text();
  }, (promise) => {
    return promise.text();
  }).then(response => {
    store.dispatch('SET_NOT_BUSY');

    successCallback(response);
  });
};
Donnie
  • 6,229
  • 8
  • 35
  • 53
  • 2
    Download CSV? -> http://stackoverflow.com/questions/20300547/download-csv-file-from-web-api-in-angular-js/20300591#20300591 – adeneo Oct 11 '16 at 20:39
  • there seems to be an issue with the formal parameters of your `exportCsv` function. You have a parameter called `grids` which is never used in the function. And as you provide only 2 parameters in your call to `exportCsv`, the `successCallback` parameter is not set to your callback function and stays undefined, – the_tiger Oct 11 '16 at 20:58
  • 1
    The browser's popup blocker is probably blocking it. You can only call `window.open()` in the handler for a user-initiated event. Calling it in the AJAX response handler disconnects it from the user event. – Barmar Oct 11 '16 at 21:30
  • @the_tiger I think it's correct. If I change that `window.open()` to a `console.log()` for example, it works. – Donnie Oct 12 '16 at 14:41
  • @Barmar You're right. That's what's happening. – Donnie Oct 12 '16 at 14:43
  • Yep @adeneo. Your solution worked. Care to leave it as an answer to I can accept? – Donnie Oct 12 '16 at 14:48

0 Answers0