溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Android WebView userAgent 設(shè)置為桌面UA實(shí)例

發(fā)布時(shí)間:2020-08-24 03:52:07 來源:腳本之家 閱讀:424 作者:輝son 欄目:移動(dòng)開發(fā)

最近一個(gè)大屏項(xiàng)目中使用到支付寶掃碼支付,但是webview加載掃碼支付鏈接時(shí)會(huì)自動(dòng)跳轉(zhuǎn)到移動(dòng)版頁面,網(wǎng)上查找怎么設(shè)置,沒找到解決方案。于是自己隨便試了下

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

webview.getSettings().setUserAgentString("電腦");

竟然真的可以。

userAgent可以設(shè)置瀏覽器標(biāo)識(shí),Android/iphone/ipod/ipad/PC等,這個(gè)應(yīng)該有做類似模糊搜索一樣,傳相近的值就可以;它就會(huì)自動(dòng)加載桌面版頁面或移動(dòng)版頁面。前提是這些頁面要有桌面版頁面和移動(dòng)版頁面,并且做了ua判斷跳轉(zhuǎn)相應(yīng)頁面。如果傳的ua識(shí)別不出來將自動(dòng)加載桌面版頁面。

補(bǔ)充知識(shí):自定義webView的userAgent

user-Agent 用戶代理,是指瀏覽器,它的信息包括硬件平臺(tái)、系統(tǒng)軟件、應(yīng)用軟件和用戶個(gè)人偏好。用戶代理的能力和偏好可以認(rèn)為是元數(shù)據(jù)或用戶代理的硬件和軟件的特性和描述。通過自定義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在請(qǐng)求時(shí)的user-Agent 就是我們?cè)O(shè)置的這個(gè)了,如果需要在WebView 使用過程中再次變更user-Agent,則需要再通過這種方式修改user-Agent, 然后再重新實(shí)例化一個(gè)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 設(shè)置為桌面UA實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI