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.
We can configure React Native app to pass custom request headers when request is made to the server to fetch pages.
let customHeaders = {
"X-DemoApp-Version": "1.1",
"X-DemoApp-Type": "demo-app-react-native",
};
While invoking WebView component we can pass customHeaders
as shown below.
renderWebView() {
return (
<WebView
source={ {uri: this.props.url, headers: customHeaders} }
/>
)
}
React Native also allows us to pass "userAgent" as a prop. However it is only supported by android version of React Native.
renderWebView() {
return (
<WebView
source={ {uri: this.props.url} }
userAgent="demo-react-native-app"
/>
)
}
For iOS, we would need to add the following lines to our AppDelegate.m to set the userAgent.
NSString *newAgent = @"demo-react-native-app";
NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
If this blog was helpful, check out our full blog archive.