iOS交互h5——user-agent


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。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM