Ajax request: Refused to set unsafe header

user411103 picture user411103 · Oct 15, 2015 · Viewed 45.7k times · Source

I am trying to play an audio using Google Text-To-Speech. Therefore I need to post a request to their endpoint with the Referer and the User-Agent properly set. This call should return an MP3 that I can play.

However, I get "Refused to set unsafe header" errors. This is my code. How can I do it?

          $.ajax({
            url: 'http://translate.google.com/translate_tts?ie=UTF-8&q=Hello&tl=en&client=t',
            beforeSend: function(xhr) {
                 xhr.setRequestHeader("Referer", "http://translate.google.com/");
                 xhr.setRequestHeader("User-Agent", "stagefright/1.2 (Linux;Android 5.0)");
            }, success: function(data){
                el.mp3 = new Audio(data);
                el.mp3.play();
            }
          });

Answer

Quentin picture Quentin · Oct 15, 2015

You can't. It is impossible.

The specification requires that the browser abort the setRequestHeader method if you try to set those headers.

If you need to set those headers then you'll need to make the request from your server and not your visitor's browser.

(That said, if you need to be deceptive about the user agent or referer then you are probably trying to use the service in a fashion that the owner of it does not want, so you should respect that and stop trying).

Also check the "Fetch forbidden header names".