Obromios Obromios - 3 months ago 36
Android Question

Set user agent with WebView with react-native

I want to modify the user agent string in a WebView so that on the server side I can detect that the request has come from my react-native app. I want to do this using the source prop in the WebView.

How do I do this for IOS and Android?


You just can set it as a prop in your WebView.

I'm doing the following:

on iOS (I set the userAgent in AppDelegate.m)

NSString *deviceType = [UIDevice currentDevice].model;
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
NSString *oldAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSString *newAgent = [oldAgent stringByAppendingString:@" MYAPPNAME - iOS - "];
newAgent = [newAgent stringByAppendingString:deviceType];
NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];

on Android (I set the userAgent in JS in my WebView):

    userAgent={DeviceInfo.getUserAgent() + " - MYAPPNAME - android "}   
    source={{uri: this.state.url}} />

now I'm always having a userAgent like "DeviceInfo - MYAPPNAME - Platform". We're doing the same like you and it works how it's supposed to do.