Android WebView userAgent 设置为桌面UA实例

时间:2022-07-27
本文章向大家介绍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实例就是小编分享给大家的全部内容了,希望能给大家一个参考。