Search code examples
javascriptjqueryutf-8xmlhttprequestwindows-1252

Force encoding used in XHR request


In a browser extension I'm developing, I'm doing an XHR request to load some data, using jQuery:

$.get(url).done(function(data, textStatus) {
    console.log(data);
})

The remotely-loaded data is a windows-1252 encoded CSV file served with Content-disposition:attachment and without mime-type/charset header (I don't have control on the backend, so I can't fix that).

How can I force the browser to decode the response as windows-1252 instead of utf-8 as it apparently currently does?


Solution

  • As hinted by my previous research and the first answers, I couldn't find a way to do what I wanted using jQuery. I worked around the issue by using a vanilla XMLHttpRequest with responseType=blob, as explained in https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data

    var oReq = new XMLHttpRequest();
    oReq.open("GET", url, true);
    oReq.responseType = "blob";
    oReq.onload = function(e) {
        var blob = new Blob([oReq.response], { type : 'text\/csv' });
        account.data = blob;
    }
    oReq.onerror = function(e){
        ...
    }
    oReq.send();
    

    Fortunately, I was already using a Blob to post the data back to the server so I'm actually saving a decoding/encoding step here...