当前位置: 移动技术网 > IT编程>移动开发>Android > Android WebView userAgent 设置为桌面UA实例

Android WebView userAgent 设置为桌面UA实例

2020年05月11日  | 移动技术网IT编程  | 我要评论

花呗取现 唐朝安全快,邢台华澳专修学院,yumaoqiu

最近一个大屏项目中使用到支付宝扫码支付,但是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实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网