React Native WebView

Learn via video courses
Topics Covered

Overview

WebView in React Native provide developers with the ability to use various web elements within their applications. These web elements encompass a wide range, spanning from complete webpage applications to basic HTML files. The react-native-webview package offers a convenient method for seamlessly integrating WebView into React Native apps. Serving as a community-supported WebView component for React Native, it serves as an alternative to the previously included WebView that has since been eliminated from the core framework.

What is React Native WebView?

React Native WebView is a component that allows developers to embed web content within React Native applications. It acts as a bridge between the native WebView components of different platforms (such as UIWebView for iOS and WebView for Android) and provides a consistent interface for rendering web content. With React Native WebView, developers can display webpages, web applications, or HTML files directly within their React Native apps.

Prerequisites

In my personal experience, I find Expo to be a valuable tool for React Native app development. Therefore, I suggest installing the Expo client on your machine by executing the following command:

In addition to utilizing Expo, I recommend using Visual Studio Code or a comparable text editor. Moreover, having a foundational understanding of JavaScript, React/React Native, and HTML will greatly benefit you as you navigate through this tutorial.

React Native WebView API References

This document presents the existing public attributes and functions associated with the React Native WebView component.

Source:

The WebView component allows you to load static HTML or a URI (with optional headers). It's important to note that when using static HTML, you need to set the originWhitelist to "*".

The source object can have either of the following formats:

Load URI:

  • URI (String): Specifies the URI to be loaded in the WebView. This can be a local or remote file. You can modify it using React state or props to navigate to a different page.
  • Method (String, Optional): Indicates the HTTP method to be used. If not specified, it defaults to GET. On Android and Windows, the supported methods are limited to GET and POST.
  • Headers (Object, Optional): Provides additional HTTP headers to be sent with the request. On Android, this can only be used with GET requests. For more details on setting custom headers, refer to the Guide.
  • Body (String, Optional): Represents the HTTP body to be sent with the request. It should be a valid UTF-8 string and will be sent as-is, without any additional encoding such as URL-escaping or base64. On Android and Windows, this can only be used with POST requests.

Static HTML:
When utilizing static HTML, it is important to ensure that the WebView property originWhiteList is set to '*'. In certain cases where video embeds are involved (such as Twitter or Facebook posts containing videos), it is necessary to specify the baseUrl for proper video playback functionality.

The parameter html (string) represents a fixed HTML page that will be shown within the WebView. On the other hand, the "baseUrl" (string) denotes the base URL that will be utilized for any relative links present in the HTML. Additionally, the same baseUrl is utilized as the origin header for CORS requests initiated from WebView.

TypeRequired
objectNo

automaticallyAdjustContentInsets:

This parameter determines whether the content inset should be adjusted for web views positioned behind a navigation bar, tab bar, or toolbar. By default, its value is set to true.

TypePlatformRequired
booliOSNo

automaticallyAdjustsScrollIndicatorInsets:

This parameter determines whether the scroll indicator inset should be modified for web views that are positioned behind a navigation bar, tab bar, or toolbar. By default, its value is set to false. (Applicable from iOS 13 onwards)

TypePlatformRequired
booliOS(13+)No

injectedJavaScript:

Configure this function to supply JavaScript code that will be inserted into the webpage once the document has finished loading, but before other subresources complete loading.

Ensure that the provided string is of a valid type (true is acceptable) and does not cause any exceptions.

For iOS, refer to WKUserScriptInjectionTimeAtDocumentEnd. It is important to define an onMessage handler, even if it has no specific operation, to ensure the execution of the code.

TypeRequiredPlatform
stringNoiOS, Android, macOS, Windows

To gain further insight, we recommend referring to the comprehensive guide on establishing communication between JavaScript and Native systems.

Please take note that the Windows operating system lacks inherent functionality for displaying alerts. Consequently, any attempts to utilize alert-related scripts will not yield the desired outcome.

For instance, you can transmit a JSON object containing the window.location data through the postMessage method, which will be subsequently processed by the onMessage function.

injectedJavaScriptBeforeContentLoaded:

Configure this setting to include JavaScript code that will be injected into the webpage once the document element is generated but before the completion of other supplementary resources.

Ensure that the provided string is valid (where 'true' is acceptable) and does not result in any exceptions being thrown.

For iOS, refer to WKUserScriptInjectionTimeAtDocumentStart.

TypeRequiredPlatform
stringNoiOS, macOS, Android (experimental)

To gain further insights, it is recommended to refer to the comprehensive guide titled "Communicating between JS and Native." For instance, you can utilize the postMessage method to transmit a JSON object containing the window.location data, which can then be processed by the onMessage function. This functionality will be accessible through the window.ReactNativeWebView.postMessage method.

injectedJavaScriptForMainFrameOnly:

When set to true (which is the default and required for Android), the injectedJavaScript is exclusively loaded into the main frame.

On the other hand, when set to false (supported only on iOS and macOS), the injectedJavaScript is loaded into all frames, including iframes.

TypeRequiredPlatform
boolNoiOS and macOS (only true supported for Android)

injectedJavaScriptBeforeContentLoadedForMainFrameOnly:

When set to true (the default option and mandatory for Android), the injectedJavaScriptBeforeContentLoaded is loaded exclusively into the main frame.

On the other hand, if set to false (limited to iOS and macOS), it will be loaded into all frames, including iframes.

TypeRequiredPlatform
boolNoiOS and macOS (only true supported for Android)

mediaPlaybackRequiresUserAction:

The "Boolean" feature determines whether user interaction, such as tapping, is necessary for HTML5 audio and video elements to begin playing. By default, the value is set to true. Please note that on iOS devices, some videos may experience loading issues when the default value is true. Changing it to false can potentially resolve this problem. This feature applies to Android API versions 17 and above.

TypeRequiredPlatform
boolNoiOS, Android, macOS

nativeConfig:

Modify the default component utilized for rendering the WebView. This allows for a customized native WebView that employs the identical JavaScript as the initial WebView.

The nativeConfig property anticipates an object that includes the following attributes:

  • component (any)
  • props (object)
  • viewManager (object)
TypeRequiredPlatform
objectNoiOS, Android, macOS

onError:

The function is triggered when there is a failure in loading the WebView.

TypeRequired
functionNo

Example:

onLoad:

The invoked function when the WebView completes its loading process.

Example:

The function assigned to onLoad is invoked when a SyntheticEvent is triggered, encapsulating a nativeEvent that includes the following attributes:

  • canGoBack
  • canGoForward
  • loading
  • target
  • title
  • url

onLoadEnd:

The function gets triggered when the WebView either successfully loads or encounters an error.

Example:

onLoadStart:

The function that gets called when the WebView initiates the loading process.

onLoadProgress:

The function that is called when the WebView is in the process of loading.

Example:

onHttpError:

The function is called when an http error is encountered by WebView.

Example:

onRenderProcessGone:

The invoked function when the WebView process on Android crashes or gets terminated by the operating system.

Example:

The function provided to onRenderProcessGone is invoked with a SyntheticEvent that encapsulates a nativeEvent containing the following attributes:

onContentProcessDidTerminate:

The function is activated when the WebView content process comes to an end.

In iOS, web views utilize a distinct process for rendering and managing web content. WebKit triggers this method when the process associated with the specific web view terminates due to various reasons. It is important to note that the termination may not necessarily be caused by a crash. For example, since iOS WebViews are not counted as part of the app's overall RAM usage, they can be terminated independently of the app to free up memory for newly opened apps by the user. It is common for WebViews to be terminated after a certain period of time when running in the background.

Example:

Installing React Native WebView Package

Install the React Native WebView package using npm or Yarn.

Run one of the following commands:

For Yarn users:

How to Create a Basic URL Structure?

To ensure simplicity, our approach involves incorporating the code directly into the App.js file without generating any supplementary files.

The most straightforward method of integrating a WebView into your React Native app is by assigning a URL as the source for your WebView component.

Paste below code in App.js:

To utilize the WebView component, it is necessary to import it, as demonstrated in line 4. Following that, you simply need to assign the source props.

It should be noted that the source prop accepts an object as its value. In this instance, we are supplying a URI:

Output:

How to Create a Basic URL Structure

How to Write the Basic Inline HTML

One popular method for assigning a source to your WebView involves composing inline HTML code. To illustrate this, we will begin with an extremely basic example.

Paste below code in App.js:

Output:

How to Write the Basic Inline HTML

The main distinction between the current code and the previous one lies in the utilization of inline HTML as the source for the WebView component, specified as source={{ html: htmlcode }}.

We have established the constant htmlcode. Which is a string that contains an h1 tag, an h2 tag, and a body tag enclosing them. We defined basic inline styles to center the elements and apply background colors.

This demonstrates how effortlessly you can render your customized HTML code. But, what if you need to incorporate JavaScript for additional functionality, such as dynamic features? Fortunately, React Native WebView provides a solution to this issue!

Linking JavaScript with React Native

To understand how linking javascript with react native works in this scenario let's consider the below code.

Output:

Linking JavaScript with React Native

Upon examining the WebView component, it becomes c that three new properties have been introduced: onMessage, injectedJavaScript, and injectedJavaScriptBeforeContentLoaded.

The JavaScript code assigned to the injectedJavaScript property executes only once, after the initial resource load. Even if the site is refreshed, the code will not execute again.

Our script, named runFirst, is located in lines 5-14. Within this script, we first trigger a render message and then modify the text of the h1 and h2 elements. All of these actions are wrapped in a setTimeout function to execute the script after a delay of 1 second.

The script provided in the injectedJavaScriptBeforeContentLoaded property executes before the first page load. The corresponding script, runBeforeFirst, is found in lines 16-19. However, this script does not affect the visual aspects of our app. The onMessage property is necessary, even though the function within it is currently empty.

Using the injectjavascript Method

The injectJavaScript method in react-native-webview allows you to execute JavaScript code within the WebView component. It is commonly used to interact with the web content loaded in the WebView from the React Native application. Let's understand injectJavascript method with the help of an example.

Output:

Using the injectjavascript Method In the example above, we create a WebView component and define a JavaScript code string in the injectScript variable. This code is responsible for finding an HTML element with the ID "myElement" and changing its inner HTML content.

Inside the handleWebViewLoad function, we access the webViewRef using the current property and call the injectJavaScript method, passing the injectScript code as a parameter. This triggers the execution of the injected JavaScript code within the WebView.

By using injectJavaScript, you can manipulate the web content, perform actions, or retrieve data from the WebView within your React Native application.

FAQs

Q. How can I use React Native WebView in my application?

A. To use React Native WebView, import the component from the 'react-native-webview' package and include it in your JSX code. You can provide a source URL or HTML content to the WebView component to load the desired web content.

Q. How can I handle events or listen to navigation changes in React Native WebView?

A. React Native WebView offers various event handlers and navigation-related properties. You can use the onMessage event to receive messages sent from the web content, the onNavigationStateChange event to track navigation changes, and the onLoad event to perform actions when the web content finishes loading.

Q. Can I interact with the web content loaded in React Native WebView?

A. Yes, you can interact with the web content by using methods provided by the WebView component. For example, you can use the injectJavaScript method to execute JavaScript code within the WebView or the postMessage method to communicate between the web content and your React Native application.

Conclusion

  • React Native WebView is a valuable component that allows developers to incorporate web content seamlessly into their React Native applications.
  • With React Native WebView, developers can display webpages, web applications, or HTML files directly within their apps.
  • The component offers flexibility in terms of loading sources, such as static HTML or URIs, and provides various customization options. Developers can interact with the web content using methods like injectJavaScript, which enables executing JavaScript code within the WebView.
  • React Native WebView is cross-platform and works consistently on both iOS and Android devices.
  • It is well-documented, making it easier for developers to integrate and utilize this powerful component in their React Native projects.