zoukankan      html  css  js  c++  java
  • iOS UIWebView 修改user-agent

    WebView 没有提供设置user-agent 的接口,无论是设置要加载的request,还是在delegate 中设置request,经测试都是无效的。如下:

    方案一:

    1. NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];  
    2. [request addValue:@"Jiecao/2.4.7" forHTTPHeaderField:@"user-agent"];  
    3. [self.webView loadRequest:request];  

    无效!!!


    方案二:

    1. #pragma mark - webview delegate  
    2.   
    3. - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {  
    4.     NSMutableURLRequest *req = (NSMutableURLRequest *)request;  
    5.     [req addValue:@"Jiecao/2.4.7" forHTTPHeaderField:@"user-agent"];  
    6. }  


    无效!!!


    我的需求是不光要能更改user-agent,而且要保留WebView 原来的user-agent 信息,也就是说我需要在其上追加信息。在stackOverflow上搜集了多方答案,最终汇总的解决方案如下:

    在启动时,比如在AppDelegate 中添加如下代码:

    1. //get the original user-agent of webview  
    2. UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];  
    3. NSString *oldAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];  
    4. NSLog(@"old agent :%@", oldAgent);  
    5.   
    6. //add my info to the new agent  
    7. NSString *newAgent = [oldAgent stringByAppendingString:@" Jiecao/2.4.7 ch_appstore"];  
    8. NSLog(@"new agent :%@", newAgent);  
    9.   
    10. //regist the new agent  
    11. NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil nil];  
    12. [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];  


    这样,WebView在请求时的user-agent 就是我们设置的这个了,如果需要在WebView 使用过程中再次变更user-agent,则需要再通过这种方式修改user-agent, 然后再重新实例化一个WebView。


    参考:

    http://stackoverflow.com/questions/478387/change-user-agent-in-uiwebview-iphone-sdk/23654363#23654363

  • 相关阅读:
    自己修改的两个js文件
    .net4缓存笔记
    使用.net的Cache框架快速实现Cache操作
    关于招聘面试(转)
    PHP中获取当前页面的完整URL
    Linux在本地使用yum安装软件(转)
    Phalcon的学习篇-phalcon和devtools的安装和设置
    GY的实验室
    aip接口中对url参数md5加密防篡改的原理
    nginx 多站点配置方法集合(转)
  • 原文地址:https://www.cnblogs.com/huangh/p/4816001.html
Copyright © 2011-2022 走看看