Working with WebViews
1. Using WebView Component
Example: Basic WebView Usage
<WebView
source={{ uri: "https://reactnative.dev" }}
style={{ flex: 1 }}
/>
| Property | Type | Description |
|---|---|---|
| source | object | string |
URL or HTML content to load in the WebView |
| style | object |
Styling for the WebView component |
| javaScriptEnabled | boolean |
Enables or disables JavaScript execution (default: true) |
| scalesPageToFit | boolean |
Controls whether the page scales to fit (default: true) |
| startInLoadingState | boolean |
Shows loading state before content loads (default: false) |
Note: On Android, WebView requires the
INTERNET permission in AndroidManifest.xml.
Warning: Avoid using inline JavaScript in HTML content as it may not execute properly.
2. Loading URL Content
| Property | Values | Description |
|---|---|---|
| source | { uri: 'https://example.com' } |
URL to load in the WebView |
| source | { html: '<html><body>Hello</body></html>' } |
HTML string to load in the WebView |
Example: Loading a URL
import { WebView } from 'react-native-webview';
<WebView
source={{ uri: 'https://reactnative.dev' }}
style={{ flex: 1 }}
/>
Example: Loading HTML Content
import { WebView } from 'react-native-webview';
<WebView
source={{ html: '<html><body><h1>Hello World</h1></body></html>' }}
style={{ flex: 1 }}
/>
Note: Ensure that the URL or HTML content is properly escaped to avoid security issues.
3. Loading HTML Strings
Example: Loading Static HTML
import React from 'react';
import { WebView } from 'react-native';
const htmlString = `
<html>
<head>
<style>
body { font-family: Arial, sans-serif; }
.highlight { background-color: yellow; }
</style>
</head>
<body>
<h1>Hello from WebView</h1>
<p class="highlight">This content is loaded from a string.</p>
</body>
</html>`;
const WebViewExample = () => {
return (
<WebView
source={{ html: htmlString }}
style={{ flex: 1 }}
/>
);
};
export default WebViewExample;
| Property | Values | Description |
|---|---|---|
| source | { html: string } |
HTML content to load as a string |
| style | object |
Style object for WebView layout |
Note: The HTML string must be properly escaped for React Native to render it correctly.
4. Handling Navigation State Changes
| Property | Description | Values |
|---|---|---|
| onNavigationStateChange | Callback function when navigation state changes | function |
Example: Handling Navigation State Changes
import React, { useState } from 'react';
import { WebView } from 'react-native';
const MyWebView = () => {
const [canGoBack, setCanGoBack] = useState(false);
const [canGoForward, setCanGoForward] = useState(false);
const handleNavigationStateChange = (navState) => {
setCanGoBack(navState.canGoBack);
setCanGoForward(navState.canGoForward);
};
return (
<WebView
source={{ uri: 'https://example.com' }}
onNavigationStateChange={handleNavigationStateChange}
/>
);
};
export default MyWebView;
Note: The
onNavigationStateChange prop provides a navigation state object with properties like canGoBack, canGoForward, and loading.
5. Implementing JavaScript Injection
Example: Injecting JavaScript into WebView
import React from 'react';
import { WebView } from 'react-native';
const InjectJSExample = () => {
const injectedJavaScript = `
document.body.style.backgroundColor = 'lightblue';
console.log('JavaScript injected!');
`;
return (
<WebView
source={{ uri: 'https://example.com' }}
injectedJavaScript={injectedJavaScript}
/>
);
};
export default InjectJSExample;
| Property | Description | Values |
|---|---|---|
| injectedJavaScript | JavaScript code to inject into the WebView | string |
| injectedJavaScriptBeforeContentLoaded | JavaScript to inject before content is loaded | string |
Note: The injected JavaScript runs in the context of the WebView and has access to the DOM.
Warning: Be cautious with JavaScript injection as it can lead to security vulnerabilities if not handled properly.
6. Communicating Between WebView and Native
Example: Sending Data from Native to WebView
import { WebView } from 'react-native';
const htmlContent = '<html><body><script>window.postMessage("Hello from WebView")</script></body></html>';
<WebView
source={{ html: htmlContent }}
onMessage={(event) => {
console.log("Received from WebView:", event.nativeEvent.data);
}}
/>
| Method | Description | Notes |
|---|---|---|
| postMessage() | Sends data from WebView to Native | Must be called inside WebView JS context |
| onMessage | Callback for receiving messages from WebView | Receives event with data field |
Note: The
postMessage() method is only available in the WebView's JavaScript context. It cannot be called from native code directly.
Example: Sending Data from WebView to Native
import { WebView } from 'react-native';
const htmlContent = '<html><body><script>
window.ReactNativeWebView.postMessage("Hello from WebView");
</script></body></html>';
<WebView
source={{ html: htmlContent }}
onMessage={(event) => {
console.log("Received from WebView:", event.nativeEvent.data);
}}
/>
Example: Using Native Module to Send Data
import { WebView } from 'react-native';
const htmlContent = '<html><body><script>
window.ReactNativeWebView.postMessage("Hello from WebView");
</script></body></html>';
<WebView
source={{ html: htmlContent }}
onMessage={(event) => {
// Handle message from WebView
console.log("Received from WebView:", event.nativeEvent.data);
}}
/>
7. Handling WebView Errors
Example: Basic Error Handling in WebView
import React from 'react';
import { WebView } from 'react-native';
const MyWebView = () => {
const [error, setError] = React.useState(null);
const onError = (errorEvent) => {
console.error("WebView error:", errorEvent);
setError(errorEvent);
};
return (
<WebView
source={{ uri: 'https://example.com' }}
onError={onError}
/>
);
};
export default MyWebView;
| Error Event Property | Description | Notes |
|---|---|---|
| code | number |
Unique error code from the WebView engine |
| description | string |
Human-readable error description |
| domain | string |
Domain of the error (e.g., "NSURLError") |
| url | string |
The URL that caused the error |
Note: The error event is not always triggered for all types of errors, particularly network or rendering issues. It's best to combine it with
onLoadEnd and onLoadStart for comprehensive error tracking.
Error Handling Strategies
- Display a user-friendly error message when
onErroris triggered. - Log errors for debugging and analytics purposes.
- Implement retry logic or fallback content if the error is recoverable.
8. Setting Custom Headers
| Property | Values | Description |
|---|---|---|
| headers | Object |
Custom headers to be sent with the request. Each key-value pair represents a header field and its value. |
Example: Setting Custom Headers in WebView
{'<WebView\n source={{\n uri: \'https://example.com\',\n headers: {\n \'Authorization\': \'Bearer token123\',\n \'X-Custom-Header\': \'custom-value\'\n }\n }}\n style={{ flex: 1 }}\n/>'}
9. Implementing Cookie Management
Example: Setting and Getting Cookies
import { WebView } from 'react-native';
import CookieManager from '@react-native-cookies/cookies';
const setCookies = async () => {
await CookieManager.set('https://example.com', {
name: 'session_id',
value: 'abc123',
domain: '.example.com',
path: '/',
expires: new Date().getTime() + 3600 * 1000,
});
};
const getCookies = async () => {
const cookies = await CookieManager.get('https://example.com');
console.log(cookies);
};
const WebViewWithCookies = () => {
return (
<WebView
source={{ uri: 'https://example.com' }}
javaScriptEnabled={true}
/>
);
};
| Method | Description | Parameters | Notes |
|---|---|---|---|
| set() | Sets a cookie for a given URL | url: string, cookie: CookieObject |
Cookie object includes name, value, domain, path, and expiration |
| get() | Gets all cookies for a given URL | url: string |
Returns a promise with all cookies as an object |
| clear() | Clears all cookies for a given URL | url: string |
Removes all cookies associated with the URL |
Note: Cookie management in WebView requires the
@react-native-cookies/cookies library. Ensure proper permissions are set in AndroidManifest.xml and Info.plist for cookie handling.
10. Configuring WebView Security
| Property | Values | Description |
|---|---|---|
| domStorageEnabled | true | false |
Enables or disables DOM storage. Default is false. |
| javaScriptEnabled | true | false |
Enables or disables JavaScript execution. Default is true. |
| thirdPartyCookiesEnabled | true | false |
Enables or disables third-party cookie support. Default is true. |
| scalesPageToFit | true | false |
Enables or disables page scaling. Default is true. |
| geolocationEnabled | true | false |
Enables or disables geolocation. Default is false. |
| allowFileAccessFromFileURLs | true | false |
Allows file access from file URLs. Default is false. |
| allowUniversalAccessFromFileURLs | true | false |
Allows universal access from file URLs. Default is false. |
Example: WebView Security Configuration
import React from 'react';
import { WebView } from 'react-native';
const WebViewSecurity = () => {
return (
<WebView
source={{ uri: 'https://example.com' }}
domStorageEnabled={true}
javaScriptEnabled={true}
thirdPartyCookiesEnabled={true}
scalesPageToFit={false}
geolocationEnabled={false}
allowFileAccessFromFileURLs={false}
allowUniversalAccessFromFileURLs={false}
/>
);
};
export default WebViewSecurity;
Note: Setting
javaScriptEnabled to false can improve security by preventing script execution.
Warning: Enabling
allowUniversalAccessFromFileURLs can pose security risks and should be avoided in production.