8

I'm using phonegap / cordova for developing an Android app.

The app has to read files on a remote server. Therefore I'm using AJAX (jQuery). The problem is: The remote server redirects all connections from mobile devices to a mobile version, which doesn't work for me, so I have to change the User Agent to a desktop browser.

How can I do this? I've seen a solution for iOS. Is something like this possible for Android?


Edit: I found a solution myself:

Just add

WebSettings w = this.appView.getSettings();      
w.setUserAgentString("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1");

to /src/com/a/b/c.java in onCreate-method.

Community
  • 1
  • 1
ninov
  • 629
  • 1
  • 6
  • 17
  • 1
    This did not work for me. Any ideas? – Danation Jan 29 '13 at 01:19
  • 2
    You can add an answer to your own question - you don't have to edit it in to the question itself. It would be a lot neater if you edit again and did that. – rjmunro Apr 09 '13 at 14:10
  • @ninov I am using Cordova but I don't have any .java file. Can we call this from javascript? Does it still work as of 2017? –  Jun 25 '17 at 11:55

2 Answers2

10

put this in your onCreate method: (after super.init();)

super.appView.getSettings().setUserAgentString("Your own agent string");

this worked for me.

See for more settings: http://developer.android.com/reference/android/webkit/WebSettings.html

Leon Berenschot
  • 148
  • 1
  • 5
1

If you're looking for a more powerful http client for cordova that allows changing the user agent, or any header in that matter, try out https://github.com/aporat/cordova-plugin-fetch. it wraps around well tested native networking libraries (AFNetworking 2 on ios, and OKHttp on android).

it also follows the window.fetch, so you could use cordovaFetch on the simulators and devices, while testing on the browser with fetch.js.

Just install the plugin with

cordova plugin add https://github.com/aporat/cordova-plugin-fetch.git

and include the user agent header in any request you made.

cordovaFetch('/users.json', {
  method : 'GET',
  headers: {
   'User-Agent': 'your user agent'
 },
})
aporat
  • 5,922
  • 5
  • 32
  • 54