Set user agent with WebView with react-native
windows phone user-agent for android and ios
Android:
mWebView.getSettings().setUserAgentString("Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 920)");
IOS:
[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObject:@"Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 920)" forkey:@"UserAgent"]];
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];
This library now provides a method to get the userAgent for both ios and android:
https://github.com/react-native-community/react-native-device-info#getuseragent
this.state = {
userAgent: "",
}
componentDidMount = async () => {
this.setState({ userAgent: await DeviceInfo.getUserAgent() })
}
<WebView
source={{ uri: "https://stackoverflow.com" }}
userAgent={this.state.userAgent}
>