华域联盟 Andriod Android WebView userAgent 设置为桌面UA实例

Android WebView userAgent 设置为桌面UA实例

最近一个大屏项目中使用到支付宝扫码支付,但是webview加载扫码支付链接时会自动跳转到移动版页面,网上查找怎么设置,没找到解决方案。于是自己随便试了下

webview.getSettings().setUserAgentString("PC");

webview.getSettings().setUserAgentString("电脑");

竟然真的可以。

userAgent可以设置浏览器标识,Android/iphone/ipod/ipad/PC等,这个应该有做类似模糊搜索一样,传相近的值就可以;它就会自动加载桌面版页面或移动版页面。前提是这些页面要有桌面版页面和移动版页面,并且做了ua判断跳转相应页面。如果传的ua识别不出来将自动加载桌面版页面。

补充知识:自定义webView的userAgent

user-Agent 用户代理,是指浏览器,它的信息包括硬件平台、系统软件、应用软件和用户个人偏好。用户代理的能力和偏好可以认为是元数据或用户代理的硬件和软件的特性和描述。通过自定义user-Agent ,我们可以给特定的浏览器读取特定的一些消息。

  UIWebView * webView = [[UIWebView alloc] initWithFrame:CGRectZero];
  NSString * oldAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
  NSLog(@"old agent :%@", oldAgent);

  //add my info to the new agent
  NSString * newAgent = [oldAgent stringByAppendingString:@" SuGrand/2.4.7 ch_appstore"];

  // or updata my info to the new agent
//  NSString * newAgent = [NSString stringWithFormat:@"Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12H141"];

  NSLog(@"new agent :%@", newAgent);

  //regist the new agent
  NSDictionary * dic = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
  [[NSUserDefaults standardUserDefaults] registerDefaults:dic];

这样,WebView在请求时的user-Agent 就是我们设置的这个了,如果需要在WebView 使用过程中再次变更user-Agent,则需要再通过这种方式修改user-Agent, 然后再重新实例化一个WebView。

  __weak typeof(self) weakSelf = self;

  [self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
    __strong typeof(weakSelf) strongSelf = weakSelf;

    NSLog(@"old agent :%@", result);

    NSString *userAgent = result;
    NSString *newUserAgent = [userAgent stringByAppendingString:@" Appended Custom User Agent"];

    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];

    strongSelf.webView = [[WKWebView alloc] initWithFrame:strongSelf.view.bounds];

    // After this point the web view will use a custom appended user agent
    [strongSelf.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
      NSLog(@"new agent :%@", result);
    }];
  }];

以上这篇Android WebView userAgent 设置为桌面UA实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持华域联盟。

本文由 华域联盟 原创撰写:华域联盟 » Android WebView userAgent 设置为桌面UA实例

转载请保留出处和原文链接:https://www.cnhackhy.com/108311.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

解决Android Studio Gradle Metadata特别慢的问题

关于WebView 重定向行为导致的多次加载的问题

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们