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?
WebViews offer developers opportunities to render any web components in a React Native application. A web component can be anything from a whole webpage/application or just a simple HTML file. The package react-native-webview makes it super simple to embed WebViews into your React Native apps!
To set user-agent string of WebView, call its getSettings(). setUserAgentString(ua); where ua is is your user-agent string. remark: to check what user-agent your browser set, browse to http://whatsmyuseragent.com/, allows you to view details about your user agent.
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):
<WebView
userAgent={DeviceInfo.getUserAgent() + " - MYAPPNAME - android "}
ref={"WEBVIEW"}
automaticallyAdjustContentInsets={false}
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.
For Android, you only need to set userAgent
attribute, for example:
<WebView
source={{ uri: "https://stackoverflow.com" }}
userAgent="Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
/>
For iOS, you need to add the code below inside the method didFinishLaunchingWithOptions
(before the line return YES;
) in AppDelegate.m
implementation:
NSString *userAgent = @"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36";
NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:userAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With