且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Cordova应用程序中设置用户代理

更新时间:2023-11-24 20:13:28

这取决于您使用的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/&gt ;

如果您使用的是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);

}