User agent or custom header in React Native WebView

Neeraj Singh

By Neeraj Singh

on July 10, 2016

Using WebView in a React Native application allows us to reuse already built web pages.

We have seen that in most of the "web view" based applications the links in header are mostly turned in native navigational components. It means server should not be sending header if React Native component is asking for web pages. However those headers should be present if the request is not coming from the React Native app.

Passing custom request headers

We can configure React Native app to pass custom request headers when request is made to the server to fetch pages.

1let customHeaders = {
2  "X-DemoApp-Version": "1.1",
3  "X-DemoApp-Type": "demo-app-react-native",

While invoking WebView component we can pass customHeaders as shown below.

1renderWebView() {
2  return (
3    <WebView
4      source={ {uri: this.props.url, headers: customHeaders} }
5    />
6  )

Passing user agent

React Native also allows us to pass "userAgent" as a prop. However it is only supported by android version of React Native.

1renderWebView() {
2  return (
3    <WebView
4      source={ {uri: this.props.url} }
5      userAgent="demo-react-native-app"
6    />
7  )

For iOS, we would need to add the following lines to our AppDelegate.m to set the userAgent.

1NSString *newAgent = @"demo-react-native-app";
2NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
3[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.