4

This isn't the end of the world, however it would be a nice to have.

Currently building a hybrid app using Ionic 2 and I am sending requests to a server API.

I would like to have the User Agent string report the app and version (along with platform), e.g MyApp V1.0 (iOS).

Currently I am sending requests like:

http.post(my_server_url, JSON.stringify(dataToSend), options)

The options object is constructed as:

let options = {
    headers: myHeaders
};

With headers being constructed as:

let myHeaders = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('User-Agent', 'MyApp V1.0 (iOS)');

The user agent is constructed using platform specific data, the above is just a straight forward string for the purposes of this question.

The request works as expected, the data is received by the server and acted on accordingly. The server sends an appropriate request which is dealt with properly. However, when I check the headers that were actually sent, the User-Agent not the one I set.

For example, on an iPhone, I see the following User Agent (both checking via Safari developer tools, and also the server log):

Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_2 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko)

Which is based on the wrapping webview that is being used. I am therefore guessing there is some mechanism that is preventing me overriding the user agent.

As part of the same App, I am uploading files and using the cordova file transfer plugin for that. I set the headers for that transfer (which isn't using Angular http), and the user agent is correctly reported in the server logs.

Therefore, as the question states, is there a way using Angular http to set a custom User-Agent header?

jpmcc
  • 368
  • 5
  • 11

1 Answers1

2

Browsers don't allow to override the user agent header. You can install browser extensions though that allow that.

See also JQuery Ajax Request: Change User-Agent

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Unfortunately that won't help as this is a hybrid app, creating using Ionic 2 (and therefore cordova), which is compiled to a native app to be installed on the target devices, in this case iOS and Android. Therefore browser plugins are not applicable. I assume your answer is basically web browsers (including web views), disable setting the user agent. – jpmcc Oct 12 '16 at 13:44
  • 1
    ok, I think I am going to accept this answer as it is essentially correct - the web view will not allow me to change the user agent and that answers the question as set. However, I have now found how to get Cordova to override that, which is probably beyond the question as set. – jpmcc Oct 12 '16 at 13:51
  • 1
    I was incorrectly focussing on Angular rather than cordova. [This helped](http://stackoverflow.com/questions/32052221/how-i-can-set-user-agent-in-cordova-app#answer-32337353) – jpmcc Oct 12 '16 at 13:53