How i can set User Agent in Cordova App

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);

}

Leave a Comment