WKWebView 设置全局UserAgent

关键是要设置customUserAgent(>=iOS 9.0),否则执行evaluateJavaScript:@"navigator.userAgent"获取不到webView的UA:

//修改userAgent
+ (void)addToWebViewUserAgent:(NSString *)addAgent
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        WKWebView *webView = [WKWebView new];
        [webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id _Nullable oldAgent, NSError * _Nullable error) {
            if (![oldAgent isKindOfClass:[NSString class]]) {
                // 为了避免没有获取到oldAgent,所以设置一个默认的userAgent
                // Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148
                oldAgent = [NSString stringWithFormat:@"Mozilla/5.0 (%@; CPU iPhone OS %@ like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148", [[UIDevice currentDevice] model], [[[UIDevice currentDevice] systemVersion] stringByReplacingOccurrencesOfString:@"." withString:@"_"]];
            }
            
            //自定义user-agent
            if (![oldAgent hasSuffix:addAgent]) {
                NSString *newAgent = [oldAgent stringByAppendingFormat:@" DWD_HSQ/%@",addAgent];
                [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent":newAgent}];
                // 一定要设置customUserAgent,否则执行navigator.userAgent拿不到oldAgent
                webView.customUserAgent = newAgent;
            }
        }];
    });
}

你可能感兴趣的:(WKWebView 设置全局UserAgent)