Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 719
Obromios Avatar asked Apr 13 '16 06:04

Obromios


People also ask

Can we use WebView in React Native?

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!

How do I change user agent in Android WebView?

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.


2 Answers

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.

like image 123
vanBrunneren Avatar answered Oct 11 '22 16:10

vanBrunneren


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];
like image 42
shimatai Avatar answered Oct 11 '22 16:10

shimatai