Android WebView userAgent 設(shè)置為桌面UA實(shí)例
最近一個(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在請求時(shí)的user-Agent 就是我們設(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è)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 完美解決vue 中多個(gè)echarts圖表自適應(yīng)的問題2. SpringBoot+TestNG單元測試的實(shí)現(xiàn)3. Springboot 全局日期格式化處理的實(shí)現(xiàn)4. idea配置jdk的操作方法5. Docker容器如何更新打包并上傳到阿里云6. Java GZip 基于內(nèi)存實(shí)現(xiàn)壓縮和解壓的方法7. VMware中如何安裝Ubuntu8. python 浮點(diǎn)數(shù)四舍五入需要注意的地方9. JAMon(Java Application Monitor)備忘記10. vue實(shí)現(xiàn)web在線聊天功能
