Simple React Native Android module to use Android's WebView inside your app

Last update: May 8, 2022

react-native-webview-android

Simple React Native Android module to use Android's WebView inside your app (with experimental html file input support to handle file uploads in forms).

npm version npm downloads npm licence

Installation

npm install react-native-webview-android --save

Add it to your android project

  • In android/setting.gradle
...
include ':RNWebView', ':app'
project(':RNWebView').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-webview-android/android')
  • In android/app/build.gradle
...
dependencies {
  ...
  compile project(':RNWebView')
}
  • Register Module - RN >= 0.29 (in MainApplication.java)
import com.burnweb.rnwebview.RNWebViewPackage;  // <--- import

public class MainApplication extends Application implements ReactApplication {
  ......

  @Override
  protected List<ReactPackage> getPackages() {
    return Arrays.<ReactPackage>asList(
        new MainReactPackage(),
        new RNWebViewPackage()); // <------ add this line to your MainApplication class
  }

  ......

}

If you need to see the install instructions for older React Native versions look here.

Example

var React = require('react-native');
var { StyleSheet } = React;

var WebViewAndroid = require('react-native-webview-android');

var SITE_URL = "https://www.google.com";

var WebViewAndroidExample = React.createClass({
    getInitialState: function() {
      return {
        url: SITE_URL,
        // OR
        // you can use a source object like React Native Webview.
        // source {uri: string, method: string, headers: object, body: string}, {html: string, baseUrl: string}
        // Loads static html or a uri (with optional headers) in the WebView. <Just like React Native's version>
        // source: {
        //   uri: SITE_URL,
        //   headers: {
        //     ...
        //   },
        // },
        status: 'No Page Loaded',
        backButtonEnabled: false,
        forwardButtonEnabled: false,
        loading: true,
        messageFromWebView: null
      };
    },
    goBack: function() {
      // you can use this callback to control web view
      this.refs.webViewAndroidSample.goBack();
    },
    goForward: function() {
      this.refs.webViewAndroidSample.goForward();
    },
    reload: function() {
      this.refs.webViewAndroidSample.reload();
    },
    stopLoading: function() {
      // stops the current load
      this.refs.webViewAndroidSample.stopLoading();
    },
    postMessage: function(data) {
      // posts a message to web view
      this.refs.webViewAndroidSample.postMessage(data);
    },
    evaluateJavascript: function(data) {
      // evaluates javascript directly on the webview instance
      this.refs.webViewAndroidSample.evaluateJavascript(data);
    },
    injectJavaScript: function(script) {
      // executes JavaScript immediately in web view
      this.refs.webViewAndroidSample.injectJavaScript(script);
    },
    onShouldStartLoadWithRequest: function(event) {
      // currently only url & navigationState are returned in the event.
      console.log(event.url);
      console.log(event.navigationState);

      if (event.url === 'https://www.mywebsiteexample.com/') {
        return true;
      } else {
        return false;
      }
    },
    onNavigationStateChange: function(event) {
      console.log(event);

      this.setState({
        backButtonEnabled: event.canGoBack,
        forwardButtonEnabled: event.canGoForward,
        url: event.url,
        status: event.title,
        loading: event.loading
      });
    },
    onMessage: function(event) {
      this.setState({
        messageFromWebView: event.message
      });
    },
    javascriptToInject: function () {
      return `
        $(document).ready(function() {
          $('a').click(function(event) {
            if ($(this).attr('href')) {
              var href = $(this).attr('href');
              window.webView.postMessage('Link tapped: ' + href);
            }
          })
        })
      `
    },
    render: function() {
      return (
        <WebViewAndroid
          ref="webViewAndroidSample"
          javaScriptEnabled={true}
          geolocationEnabled={false}
          builtInZoomControls={false}
          injectedJavaScript={this.javascriptToInject()}
          onShouldStartLoadWithRequest={this.onShouldStartLoadWithRequest}
          onNavigationStateChange={this.onNavigationStateChange}
          onMessage={this.onMessage}
          url={SITE_URL} // or use the source(object) attribute...
          style={styles.containerWebView} />
      );

      // other attributes: source(object), html(string), htmlCharset(string), baseUrl(string), injectedJavaScript(string), disableCookies(bool), disablePlugins(bool), userAgent(string)
    }
});

var styles = StyleSheet.create({
  containerWebView: {
    flex: 1,
  }
});

Note about onShouldStartLoadWithRequest

This module has a working implementation of onShouldStartLoadWithRequest. However, the event it returns currently only includes url and navigationState.

Note about HTML file input (files upload)

This module implements an experimental support to handle file input in HTML forms for upload files. It was tested in some Android versions 4.1+, but it's possible that some device won't work OK with that new feature.

File input demo

Tips for Video (HTML5) inside WebView

To work with some html5 video player inside your Webview, I recommend you to set the android:hardwareAccelerated="true" in your AndroidManifest.xml file.

More info here: http://stackoverflow.com/questions/17259636/enabling-html5-video-playback-in-android-webview

License

MIT

GitHub

https://github.com/lucasferreira/react-native-webview-android
Comments
  • 1. js call app

    now js can call app;

    Usage:

    Carson

    <WebViewAndroid javaScriptEnabled={true} domStorageEnabled={true} scalesPageToFit={true} startInLoadingState={true} geolocationEnabled={false} builtInZoomControls={false} decelerationRate="normal" automaticallyAdjustContentInsets={false} url={url} style={styles.base} jsToApp={this._jsToApp.bind(this)} />

    _jsToApp(params) { // alert("_jsToApp"); }

    Reviewed by HancleLee at 2017-09-13 07:33
  • 2. error when compiling the application

    Hello, I have an error when compiling the application --> Error: more than one library with package name 'com.burnweb.rnwebview'

    React: 15.3.0 React-native: 0.33.0

    Reviewed by justineraze at 2016-09-13 15:40
  • 3. YouTube videos are black screen

    Hi, I tried to follow your orders to enable YouTube playback, Added android:hardwareAccelerated="true" in the <application on AndroidManifest.xml Also, tried to add some properties, followed stack overflow questions, but can't get it to work. Worth to notice that Kickstarter videos are playing fine, and I saw you added WebChromeClient to your library. If it matters, I'm trying to run it on Samsung Galaxy Note 4. Any ideas?

    Reviewed by avishayil at 2015-12-24 09:28
  • 4. Full Height cannot be set

    Hi, Thanks for the nice tool. I cannot set full height to the device to the webview in RN android app. Tried with different methods but could not get it worked. RN version is 0.13.1.

    Reviewed by MuruganDurai at 2015-12-23 22:04
  • 5. Error:Configuration with name 'default' not found.

    Hello, when adding compile project(':RNWebView') to "android/app/build.gradle", I get the following error Error:Configuration with name 'default' not found. I am running Android SDK 2.1.3 on windows 10. Please help me clarify the issue.

    Thanks, Joe

    Reviewed by joeey1984ad at 2016-09-06 21:23
  • 6. Android 0.19.0

    Hi, Followed all instructions

    1. c:\React\NativeStarter>react-native run-android .... FAILURE: Build failed with an exception.
    • Where: Build file 'C:\React\NativeStarter\android\app\build.gradle' line: 78
    • What went wrong: A problem occurred evaluating project ':app'.

      Project with path ':RNWebView' could not be found in project ':app'.

    • Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. BUILD FAILED
    1. I got BUILD SUCCESSFUL with a secod attempt 3)react-native start but get the following on start image

    Using RN 0.19.0 win10 genymotion Thanls. John

    Reviewed by johntom at 2016-02-06 23:13
  • 7. webview not showing anything

    hi

    i am trying to load a url using the webview but its not showing anything

    i have copy pasted your webviewandroid example

    this is the logs i get

    11-24 18:23:50.225 2224 2224 W art : Attempt to remove non-JNI local reference, dumping thread 11-24 18:23:50.228 2224 2224 W AwContents: onDetachedFromWindow called when already detached. Ignoring 11-24 18:23:50.394 2224 2403 D ReactNativeJS: { url: 'https://www.google.com/', 11-24 18:23:50.394 2224 2403 D ReactNativeJS: canGoForward: false, 11-24 18:23:50.394 2224 2403 D ReactNativeJS: canGoBack: false, 11-24 18:23:50.394 2224 2403 D ReactNativeJS: loading: true } 11-24 18:23:50.504 2224 2403 D ReactNativeJS: { url: 'https://www.google.co.uk/?gfe_rd=cr&ei=PKtUVte-L_Kq8weggJbABA', 11-24 18:23:50.504 2224 2403 D ReactNativeJS: canGoForward: false, 11-24 18:23:50.504 2224 2403 D ReactNativeJS: canGoBack: false, 11-24 18:23:50.504 2224 2403 D ReactNativeJS: loading: true } 11-24 18:23:51.038 2224 2224 W BindingManager: Cannot call determinedVisibility() - never saw a connection for the pid: 2224 11-24 18:23:53.103 2224 2403 D ReactNativeJS: { url: 'https://www.google.co.uk/?gfe_rd=cr&ei=PKtUVte-L_Kq8weggJbABA', 11-24 18:23:53.103 2224 2403 D ReactNativeJS: canGoForward: false, 11-24 18:23:53.103 2224 2403 D ReactNativeJS: canGoBack: false, 11-24 18:23:53.103 2224 2403 D ReactNativeJS: loading: false } 11-24 18:23:54.910 2224 2224 W BindingManager: Cannot call determinedVisibility() - never saw a connection for the pid: 2224

    i am on react native 0.14.2 .

    any help would be appreciated

    Reviewed by jawadrehman at 2015-11-24 18:25
  • 8. Geolocation in webview doesn't work when I use Navigation API

    Hello, have you by any chance tried using google maps inside the webview? Whenever I use a Navigator the webview doesn't show anything and when I use the webview on its own it works. The maps site is written in react js.

    The combination of the Navigation API and the Webview somehow disables maps with geolcation and nothing shows in the webview.

    Console has no errors.

    The iOS version of the app works fine. I am using RN0.22

    Browsing through RN code, it looks like if the parent 'View' has backgroundcolor, the maps do not show. I am not sure what the connection between geolcation inside a webview is affected by the Navigation API.

    Reviewed by eMatsiyana at 2016-03-31 18:32
  • 9. blank component

    i dont know why i get a blank screen when i use this module. im trying this out on index.js

    var WebViewAndroid = require('react-native-webview-android');
    
    import { AppRegistry } from 'react-native';
    
    class Whatever extends Component {
      render () {
        return <WebViewAndroid url='https://www.google.com' javaScriptEnabled={true}
          geolocationEnabled={false} style={{ flex: 1 }} />;
      }
    }
    
    AppRegistry.registerComponent('whatever', () => Whatever);
    
    Reviewed by spearmootz at 2018-01-02 18:59
  • 10. Added support for onShouldStartLoadWithRequest.

    This adds a solution to react-native-webview-android for onShouldStartLoadWithRequest support.

    The approach is fairly straightforward.

    For any URL load, shouldOverrideUrlLoading will initially return true - not allowing it to load. It will also dispatch the ShouldOverrideUrlLoadingEvent, triggering _onShouldOverrideUrlLoading in index.android.js. It then gets the result of onShouldStartLoadWithRequest at the react-native level if it's set on RNWebViewAndroid. A view manager command is sent back to the native side, which will take the onShouldStartLoadWithRequest result as shouldOverride included in the command and either allow the original url to load, or not load.

    To note, onShouldStartLoadWithRequest only receives an object containing url and navigationState in this initial implementation.

    Reviewed by iamarkdev at 2018-05-08 21:14
  • 11. js call app

    now js can call app;

    Usage:

    Carson

    <WebViewAndroid javaScriptEnabled={true} domStorageEnabled={true} scalesPageToFit={true} startInLoadingState={true} geolocationEnabled={false} builtInZoomControls={false} decelerationRate="normal" automaticallyAdjustContentInsets={false} url={url} style={styles.base} jsToApp={this._jsToApp.bind(this)} />

    _jsToApp(params) { // alert("_jsToApp"); }

    Reviewed by HancleLee at 2017-09-20 08:05
  • 12. is this lib butter than the normal react native webview

    i have a problem with the normal react native webview , if i open a https site , i see a blank screen but it`s load the iframe site that the site have on android 5 - lolipop , is that something that this library can solve

    Reviewed by syrakozz at 2019-01-15 13:39
  • 13. Execution failed for task ':react-native-webview-android:verifyReleaseResources'.

    Configure project :react-native-webview-android WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'. It will be removed at the end of 2018. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html WARNING: The specified Android SDK Build Tools version (25.0.0) is ignored, as it is below the minimum supported version (27.0.3) for Android Gradle Plugin 3.1.4. Android SDK Build Tools 27.0.3 will be used. To suppress this warning, remove "buildToolsVersion '25.0.0'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.

    Task :app:bundleReleaseJsAndAssets warning: the transform cache was reset. Loading dependency graph, done. bundle: Writing bundle output to: /Users/liuyang/workspace/APP/泉山区企业大数据平台_周旭/webView_qsqdsj/android/app/build/generated/assets/react/release/index.android.bundle bundle: Done writing bundle output bundle: Copying 1 asset files bundle: Done copying assets

    error: resource android:style/TextAppearance.Material.Widget.Button.Borderless.Colored not found. error: resource android:style/TextAppearance.Material.Widget.Button.Colored not found. /Users/liuyang/.gradle/caches/transforms-1/files-1.1/appcompat-v7-27.1.1.aar/407b97d568927eeb5a20fd318fadfdbf/res/values-v26/values-v26.xml:9:5-12:13: AAPT: error: resource android:attr/colorError not found.

    /Users/liuyang/.gradle/caches/transforms-1/files-1.1/appcompat-v7-27.1.1.aar/407b97d568927eeb5a20fd318fadfdbf/res/values-v26/values-v26.xml:13:5-16:13: AAPT: error: resource android:attr/colorError not found.

    /Users/liuyang/.gradle/caches/transforms-1/files-1.1/appcompat-v7-27.1.1.aar/407b97d568927eeb5a20fd318fadfdbf/res/values-v26/values-v26.xml:17:5-93: AAPT: error: style attribute 'android:attr/keyboardNavigationCluster' not found.

    /Users/liuyang/.gradle/caches/transforms-1/files-1.1/appcompat-v7-27.1.1.aar/407b97d568927eeb5a20fd318fadfdbf/res/values/values.xml:251:5-69: AAPT: error: resource android:attr/fontStyle not found.

    /Users/liuyang/.gradle/caches/transforms-1/files-1.1/appcompat-v7-27.1.1.aar/407b97d568927eeb5a20fd318fadfdbf/res/values/values.xml:251:5-69: AAPT: error: resource android:attr/font not found.

    /Users/liuyang/.gradle/caches/transforms-1/files-1.1/appcompat-v7-27.1.1.aar/407b97d568927eeb5a20fd318fadfdbf/res/values/values.xml:251:5-69: AAPT: error: resource android:attr/fontWeight not found.

    error: failed linking references.

    FAILURE: Build failed with an exception.

    • What went wrong: Execution failed for task ':react-native-webview-android:verifyReleaseResources'.

    com.android.ide.common.process.ProcessException: Failed to execute aapt

    • Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

    • Get more help at https://help.gradle.org

    BUILD FAILED in 31s 40 actionable tasks: 37 executed, 3 up-to-date

    Reviewed by ly6158 at 2018-11-27 11:39
  • 14. Promise based evaluateJavascript result

    This returns the result of the evaluation of javascript on the webview. Decided promise based was the way to go instead of opting for the easier to implement listener route

    Reviewed by lukefanning at 2018-09-14 10:26
React Native Webview with Javascript Bridge
React Native Webview with Javascript Bridge

Please take a look at this issue first React Native WebView Javascript Bridge I have been testing and reading a lot of way to safely create a bridge b

Jun 17, 2022
Full-featured web browser module for React Native apps, based on TOWebViewController
Full-featured web browser module for React Native apps, based on TOWebViewController

react-native-browser A full-featured web browser module for React Native apps, based on the awesome TOWebViewController Installation Run npm install r

May 8, 2022
A set of classes and react components to make work your react-native app in a browser. (with some limitations obviously)

React Native for Web A set of classes and react components to make work your react-native app in a browser. (with some limitations obviously) GitHub r

Jun 1, 2022
A React Native wrapper for Safari View Controller.

React Native Safari View React Native Safari View is a Safari View Controller wrapper for React Native. Documentation Install Usage Example Methods Ev

May 19, 2022
React Native adapter for building hybrid apps with Turbolinks 5
React Native adapter for building hybrid apps with Turbolinks 5

React Native Turbolinks A implementation of Turbolinks for iOS and Turbolinks Android for React Native. Getting started yarn add react-native-webview

May 17, 2022
Luna - a React Native Web boilerplate
Luna - a React Native Web boilerplate

?? Luna ?? Luna is a React Native boilerplate with minimal configuration so your app can run on Android, IOS and Web concurrently. ⭐ Features: React N

Jun 16, 2022
An easy way to integrate your React (or Preact) app into React Native app with WebView.
An easy way to integrate your React (or Preact) app into React Native app with WebView.

react-native-react-bridge An easy way to integrate your React (or Preact) app into React Native app with WebView. Why? If you'd like to run your React

Jun 16, 2022
Crosswalk's WebView for React Native on Android.

react-native-webview-crosswalk Crosswalk's WebView for React Native on Android. Dependencies 0.4.0+: react-native >=0.32.0, react >= 15.3.0 0.3.0+: re

Jun 16, 2022
A android like toast for android and ios, android use native toast, ios use UIView+Toast

React Native Toast (remobile) A android like toast for react-native support for ios and android Installation npm install @remobile/react-native-toast

Apr 4, 2022
React Native Android module to use Android's AlertDialog - same idea of AlertIOS

react-native-simpledialog-android React Native Android module to use Android's AlertDialog - same idea of AlertIOS Installation npm install react-nati

Mar 1, 2020
A Cross Platform(Android & iOS) ActionSheet with a flexible api, native performance and zero dependency code for react native. Create anything you want inside ActionSheet.
A Cross Platform(Android & iOS) ActionSheet with a flexible api, native performance and zero dependency code for react native. Create anything you want inside ActionSheet.

react-native-actions-sheet A highly customizable cross platform ActionSheet for react native. Screenshots Features Cross Platform (iOS and Android) Na

Jun 26, 2022
React-native component which renders markdown into a webview!

react-native-showdown React-native component which renders markdown into a webview! Since version 1.0.0 it requires the peer dependency react-native-w

Jan 31, 2022
React Native Webview with Javascript Bridge
React Native Webview with Javascript Bridge

Please take a look at this issue first React Native WebView Javascript Bridge I have been testing and reading a lot of way to safely create a bridge b

Jun 17, 2022
A LeafletView component using WebView and Leaflet map for React Native applications
A LeafletView component using WebView and Leaflet map for React Native applications

A LeafletView component using WebView and Leaflet map for React Native applications

Jun 19, 2022
Use Pub/Sub pattern inside your React applications easily

spacefold ?? Use Pub/Sub pattern inside your React applications easily! ?? Table of content Demo Why Usage Contribute ?? Demo Like always, a counter a

May 26, 2022
Develop a vscode sidebar webview extension

vscode-webview-extension-with-react README vscode-webview-extension-with-react is a repo to illustrate how to register a webview using react to side b

Mar 1, 2022
This module brings "Display: none" (css style) to turn on/off components from render. Using this module will improve your app performance and appearance with the enter/exit animations.
This module brings

react-native-display This module brings "Display: none" (css style) to turn on/off components from render. Using this module will improve your app per

Mar 14, 2022
Redux bindings for React Router – keep your router state inside your Redux store

redux-router This project is experimental. For bindings for React Router 1.x see here In most cases, you don’t need any library to bridge Redux and Re

Jun 18, 2022
Style your React components with simplicity using css inside your comments.

Style your React components with simplicity using css inside your comments.

Oct 12, 2021
A react native module to show toast like android, it works on iOS and Android.
A react native module to show toast like android, it works on iOS and Android.

react-native-easy-toast A react native module to show toast like android, it works on iOS and Android. Content Installation Demo Getting started API C

Jun 15, 2022