WKWebView修改userAgent

一、在UIWebView里
+ (NSString *)userAgent

{

    static NSString *gUserAgent = nil;

    if (gUserAgent == nil) {

        UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectZero];

        NSString* secretAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];

    }

    return gUserAgent;

}

在+ (void)initialize里就能获取到值

+ (void)initialize

{

 [[NSUserDefaults userDefaultWithGroup] registerDefaults:@{@"UserAgent": [self userAgent]}];

}

二、在WKWebView中

此时不能直接写在initialize里,获取不到,写在webview init之后,如:

-(WKWebView *)webView{
    if (!_webView) {
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        [_webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id obj, NSError *error) {
                NSString *gUserAgent = nil;
                if([obj isKindOfClass:[NSString class]]) {
                    [[NSUserDefaults userDefaultWithGroup] registerDefaults:@{@"UserAgent": obj}];
                }
        }];
    }
    return _webView;
}

上面的方法在首次h5还是没拿到UserAgent,建议转移到didFinishLaunchingWithOptions方法里;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

[self registerUserAgent];

}

- (void)registerUserAgent{

    WKWebView* webView = [[WKWebView alloc] initWithFrame:CGRectZero];

    [self.window addSubview:webView];

    [webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id obj, NSError *error) {

        NSString *gUserAgent = nil;

        if([obj isKindOfClass:[NSString class]]) {

            gUserAgent = obj;

            [[NSUserDefaults userDefaultWithGroup] registerDefaults:@{@"UserAgent": gUserAgent}];

        }

    }];

}

你可能感兴趣的:(WKWebView修改userAgent)