【问题标题】:How i can set User Agent in Cordova App我如何在 Cordova 应用程序中设置用户代理
【发布时间】:2015-11-10 04:45:35
【问题描述】:

如何在 Cordova 应用程序中设置用户代理?我在 VS 2015 中编写 Cordova App,我需要从其他来源下载数据。此源以 xml 格式返回数据,但当用户代理移动时,此源重定向执行移动站点。我需要将用户代理更改为桌面浏览器。数据源不是我的,无法更改。

【问题讨论】:

    标签: cordova request visual-studio-2015 user-agent


    【解决方案1】:

    这取决于您使用的是哪个版本的 cordova-android 和 cordova-ios。

    您可以通过运行cordova platform list检查平台cordova版本

    如果您在 iOS 和 Android 上使用 4.0 及以上版本,您可以在 config.xml 中设置它们,如 cordova 文档 here 中所述

    <preference name="OverrideUserAgent" value="Mozilla/5.0 My Browser" />

    如果您使用的是 4.0 及以下版本,则需要在本机代码中设置它们,如下所示。 (这段代码展示了如何追加,可以修改完全替换)

    在 iOS 中你可以这样做

    在 AppDelegate.m 中,didfinishlaunchingwithoptions 方法

    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中你可以这样做

    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】:

      使用https://github.com/LouisT/cordova-useragent等插件

      要安装插件,请使用 Cordova CLI 并输入以下内容: 科尔多瓦插件添加https://github.com/LouisT/cordova-useragent

      要设置您的用户代理: UserAgent.set(useragent)

      要获取您当前的用户代理: UserAgent.get(function(ua) { })

      要将您的用户代理设置回默认值: UserAgent.reset()

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-14
      • 1970-01-01
      相关资源
      最近更新 更多