如何在Cordova应用程序中设置用户代理 [英] How i can set User Agent in Cordova App
问题描述
如何在Cordova应用程式中设定使用者代理程式?我在VS 2015中写Cordova应用程序,我需要从其他来源下载数据。此源返回xml中的数据,但当用户代理是移动时,此源重定向做移动网站。我需要更改用户代理到桌面浏览器。数据源不是我的,不能改变它。
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.
推荐答案
这取决于您使用的cordova-android和cordova-ios版本。
It depends on which version of cordova-android and cordova-ios you are using.
您可以通过运行 cordova平台列表检查平台cordova版本
使用4.0和更高版本的iOS和Android可以在config.xml中设置它们,如cordova文档中所述此处
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 =OverrideUserAgentvalue =Mozilla / 5.0 My Browser/> ;
如果您使用的是4.0及以下版本,则需要按如下所示在本机代码中进行设置。
(此代码显示如何追加并可修改以完全替换)
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)
在iOS中,您可以执行
In iOS you can do
在AppDelegate.m中,didfinishlaunchingwithoptions方法
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"]];
在Android中,您可以执行
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);
}
这篇关于如何在Cordova应用程序中设置用户代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!