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實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: