User-Agent(用戶代理)字符串是Web瀏覽器用於聲明自身型號版本並隨HTTP請求發送給Web服務器的字符串,在Web服務器上可以獲取到該字符串。
在公司產品中,在userAgent中增加了XXXXX字段,用於標識客戶端。
我的需求是不光要能更改user-agent,而且要保留WebView 原來的user-agent 信息,也就是說我需要在其上追加信息。在stackOverflow上搜集了多方答案,最終匯總的解決方案如下:
在啟動時,比如在AppDelegate 中添加如下代碼:
//get the original user-agent of webview 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:@" Jiecao/2.4.7 ch_appstore"]; NSLog(@"new agent :%@", newAgent); //regist the new agent NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil]; [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
這樣,WebView在請求時的user-agent 就是我們設置的這個了,如果需要在WebView 使用過程中再次變更user-agent,則需要再通過這種方式修改user-agent, 然后再重新實例化一個WebView。