How i can set User Agent in Cordova App

穿精又带淫゛_ 提交于 2019-11-26 14:29:49

问题


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.


回答1:


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

}



回答2:


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



来源:https://stackoverflow.com/questions/32052221/how-i-can-set-user-agent-in-cordova-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!