且构网

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

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

更新时间:2023-11-24 18:46:10

这取决于您使用的cordova-android 和cordova-ios 版本.

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

您可以通过运行cordova platform list

如果您在 iOS 和 Android 上使用 4.0 及更高版本,您可以按照cordova 文档中的说明在config.xml 中设置它们这里

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 我的浏览器"/>

如果您使用的是 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中你可以做到

在 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"]];

在安卓中你可以做到

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

}