iOS 修改UIWebView的UserAgent


iOS和H5交互的時候,H5需要用userAgent帶一些參數,需要我們修改默認的UserAgent為自定義的。

首先,給大家普及一下userAgent的歷史,點擊UserAgent查看。

1 在Appdelegate里面register一個新的UserAgent

//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];

答案:該方法修改的是全局的UserAgent設置,[NSUserDefault stangarUserDefault]是一個單例,webView請求的時候就會從該單例中取值。注意,該方法只會修改webView的userAgent,其他的http請求的userAgent不會受影響。

最后補充一句,用的是EasyJS做交互。

 


免責聲明!

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



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