user-Agent 用户代理,是指浏览器,它的信息包括硬件平台、系统软件、应用软件和用户个人偏好。用户代理的能力和偏好可以认为是元数据或用户代理的硬件和软件的特性和描述。通过自定义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在请求时的user-Agent 就是我们设置的这个了,如果需要在WebView 使用过程中再次变更user-Agent,则需要再通过这种方式修改user-Agent, 然后再重新实例化一个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);
        }];
    }];

参考:
>>shannonchou-iOS UIWebView 修改user-agent
>>简书给-UIWebView加个自定义的User-Agent

Logo

Agent 垂直技术社区,欢迎活跃、内容共建,欢迎商务合作。wx: diudiu5555

更多推荐