美文网首页ios 参考部分
WKWebview修改userAgent

WKWebview修改userAgent

作者: 大热天晒太阳 | 来源:发表于2017-05-31 13:24 被阅读1035次

    在混合开发中,难免会遇到需要服务器判断是否为app打开该网页
    可以通过设置webview的userAgent实现判断

    参考stackoverflow

    • 如果多个webView共有一个父类的话推荐使用:
    UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    NSString *userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    NSString *newUserAgent = [userAgent stringByAppendingString:@" Appended Custom User Agent"];
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
    
    self.wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    [self.wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        NSLog(@"%@", result);
    }];
    

    这一种不使用Block,适合多个webView共用一个父类

    • 使用Block,注意block内的执行顺序
    self.wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    __weak typeof(self) weakSelf = self;
    [self.wkWebView 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.wkWebView = [[WKWebView alloc] initWithFrame:strongSelf.view.bounds];
    
        // After this point the web view will use a custom appended user agent
        [strongSelf.wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
            NSLog(@"%@", result);
        }];
    }];
    

    相关文章

      网友评论

        本文标题:WKWebview修改userAgent

        本文链接:https://www.haomeiwen.com/subject/fnzdfxtx.html