• Stars
    star
    357
  • Rank 115,332 (Top 3 %)
  • Language
    Java
  • Created over 8 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

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

More Repositories

1

react-native-flash-message

React Native flashbar and top notification alert utility
JavaScript
1,344
star
2

react-native-send-intent

React Native Android module to use Android's Intent actions for send text to shareable apps or make phone calls or opening third party apps
Java
409
star
3

react-native-android-permissions

React Native Android Permissions experimental module - Android M (6.0) permissions like to your React Native application
Java
119
star
4

react-async-fetcher

React component for asynchronous loading/fetch online data
JavaScript
50
star
5

react-native-simpledialog-android

React Native Android module to use Android's AlertDialog - same idea of AlertIOS
Java
43
star
6

react-virtualized-sectionlist

React SectionList component based in react-virtualized List
JavaScript
20
star
7

cakephp-amazonses

EmailServiceComponent to send e-mail using Amazon SES
PHP
6
star
8

react-native-progress-indicator

React Native cross-plataform module to create Progress Indicators in your apps
JavaScript
6
star
9

flythat

A simple powerful jQuery plugin to help create modals, flyovers or light-popups in your web project
JavaScript
5
star
10

react-native-platform-render

React Native swiss army knife tools to platform conditional render
JavaScript
4
star
11

cakephp-sluggable

Sluggable Behavior for CakePHP
PHP
2
star
12

db-migr

Javascript db migrations utility for SQLite, MySQL or other SQL Ansi databases
JavaScript
2
star
13

sw-php-laravel

Aula de Soluções WEB do Curso de Eng. Comp. da SATC - Exemplo de projeto com Laravel
PHP
2
star
14

slides-sw-aula-01

JavaScript
1
star
15

node-use-phpfmt

A simpler phpfmt installer for Node.js work
JavaScript
1
star
16

slides-sw-aula-07

HTML
1
star
17

slides-sw-aula-08

CSS
1
star
18

cakephp-uploader

Uploader Behavior for CakePHP
PHP
1
star
19

slides-front-end-aula-01

TypeScript
1
star