iOS wkWebView添加UserAgent(UA)

1,388 阅读1分钟

项目中会遇到多个APP或小程序共用相同的网页内容,服务器需要区分当前打开的网页是在那个APP中打开的,此时可以通过设置webview的UserAgent实现判断

- (void)setWebViewUA{//此部分内容需放到setWebUI内
    
    if (@available(iOS 12.0, *)){
        //由于iOS12的UA改为异步,所以不管在js还是客户端第一次加载都获取不到,所以此时需要先设置好再去获取(1、如下设置;2、先在AppDelegate中设置到本地)
        NSString *userAgent = [self.webView valueForKey:@"applicationNameForUserAgent"];
        NSString *newUserAgent = [NSString stringWithFormat:@"%@%@",userAgent,@"自定义UA内容"];
        [self.webView setValue:newUserAgent forKey:@"applicationNameForUserAgent"];
    }
    [self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSString *userAgent = result;
        
        if ([userAgent rangeOfString:@"自定义UA内容"].location != NSNotFound) {
            return ;
        }
        NSString *newUserAgent = [userAgent stringByAppendingString:@"自定义UA内容"];
//                NSLog(@"%@>>>%@>>>>>",userAgent,newUserAgent);
        NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent,@"UserAgent", nil];
        [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
        [[NSUserDefaults standardUserDefaults] synchronize];
         //不添加以下代码则只是在本地更改UA,网页并未同步更改
        if (@available(iOS 9.0, *)) {
            [self.webView setCustomUserAgent:newUserAgent];
        } else {
            [self.webView setValue:newUserAgent forKey:@"applicationNameForUserAgent"];
        }
    }]; //加载请求必须同步在设置UA的后面
}

loadRequest需放到设置UA之后

定义UA前

Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148

定义UA后

Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148自定义UA内容