WKWebView修改userAgent

直接上代碼:web

第一種方法:app

self.wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    __weak typeof(self) weakSelf = self;
    
    [self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        
        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(@"%@", result);
        }];
    }];

親測結果:this

Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_5 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13G36 Appended Custom User Agentlua

第二種方法:spa

UIWebView *webViews = [[UIWebView alloc] initWithFrame:self.view.bounds];
    NSString *userAgent = [webViews stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    NSString *newUserAgent = [userAgent stringByAppendingString:@" Appended Custom User Agent"];
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
    
    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    [self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        NSLog(@"%@", result);
    }];

結果:代理

Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_5 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13G36 Appended Custom User Agentcode

這種方法使UIWebView和WKWebView使用相同的用戶代理,但這種方法可能會致使問題。blog

相關文章
相關標籤/搜索