How i can set User Agent in Cordova App

How i can set User Agent in Cordova App? I write Cordova App in VS 2015 and i need download data from other source. This source return data in xml but when User Agent is mobile, this source redirect do mobile site. I need change User Agent to desktop browser. Data source is not mine, can't change it.


It depends on which version of cordova-android and cordova-ios you are using.

You can check the platform cordova versions by running cordova platform list

If you are using 4.0 and above versions for both iOS and Android you can set them in config.xml as stated in cordova documentation here

<preference name="OverrideUserAgent" value="Mozilla/5.0 My Browser" />

If you are using 4.0 and below, you need to set them in native code as below. (This code shows how to append and can be modified to replace completely)

In iOS you can do

In AppDelegate.m, didfinishlaunchingwithoptions method

UIWebView* sampleWebView = [[UIWebView alloc] initWithFrame:CGRectZero];
NSString* originalUserAgent = [sampleWebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    self.viewController.baseUserAgent = [NSString stringWithFormat:@"%@ customAgent/%@ customAgent/%@",
 originalUserAgent,CDV_VERSION,
 [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];

In Android you can do

settings = webView.getSettings();

String userAgent = settings.getUserAgentString();

if (!settings.getUserAgentString().contains("customAgent")) {
    PackageManager packageManager = this.cordova.getActivity().getPackageManager();
    double versionCode;

    try {
        versionCode = packageManager.getPackageInfo(this.cordova.getActivity().getPackageName(), 0).versionCode;
    } catch (PackageManager.NameNotFoundException e) {
        versionCode = 1.0;
    }

    userAgent += " customAgent/" + CordovaWebView.CORDOVA_VERSION + " customAgent/" + versionCode + " (233)";
    settings.setUserAgentString(userAgent);

}

Use a plugin such as https://github.com/LouisT/cordova-useragent

To install the plugin, use the Cordova CLI and enter the following: cordova plugin add https://github.com/LouisT/cordova-useragent

To set your User-Agent: UserAgent.set(useragent)

To get your current User-Agent: UserAgent.get(function(ua) { })

To set your User-Agent back to the default: UserAgent.reset()