Change User Agent in UIWebView

前端 未结 14 1968
孤城傲影
孤城傲影 2020-11-22 17:03

I have a business need to be able to customize the UserAgent for an embedded UIWebView. (For instance, I\'d like the server to respond differently if, say, a user is using

14条回答
  •  轮回少年
    2020-11-22 17:41

    I faced the same question. I want to add some info to the user-agent, also need to keep the original user-agent of webview. I solved it by using the code below:

        //get the original user-agent of webview
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
    NSString *oldAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    NSLog(@"old agent :%@", oldAgent);
    
    //add my info to the new agent
    NSString *newAgent = [oldAgent stringByAppendingString:@" Jiecao/2.4.7 ch_appstore"];
    NSLog(@"new agent :%@", newAgent);
    
    //regist the new agent
    NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
    

    Use it before you instancing webview.

提交回复
热议问题