• Stars
    star
    1,367
  • Rank 34,394 (Top 0.7 %)
  • Language
    Objective-C
  • License
    MIT License
  • Created over 9 years ago
  • Updated 6 months ago

Reviews

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

Repository Details

React Native Webview with Javascript Bridge

Please take a look at this issue first

React Native WebView Javascript Bridge

GitHub tag npm version GitHub license GitHub stars

I have been testing and reading a lot of way to safely create a bridge between react-native and webview. I'm happy to announced that the wait is over and from React-Native 0.20 and above, the bridge is fully functional.

Installation

In order to use this extension, you have to do the following steps:

in your react-native project, run npm install react-native-webview-bridge --save

iOS

  1. go to xcode's Project Navigator tab

2. right click on `Libraries` 3. select `Add Files to ...` option

4. navigate to `node_modules/react-native-webview-bridge/ios` and add `React-Native-Webview-Bridge.xcodeproj` folder

5. on project `Project Navigator` tab, click on your project's name and select Target's name and from there click on `Build Phases`

6. expand `Link Binary With Libraries` and click `+` sign to add a new one. 7. select `libReact-Native-Webviwe-Bridge.a` and click `Add` button.

8. clean compile to make sure your project can compile and build.

Android

  1. add the following import to MainApplication.java (MainActivity.java if RN < 0.29) of your application
import com.github.alinz.reactnativewebviewbridge.WebViewBridgePackage;
  1. add the following code to add the package to MainApplication.java (MainActivity.java if RN < 0.29)
protected List<ReactPackage> getPackages() {
        return Arrays.<ReactPackage>asList(
            new MainReactPackage(),
                new WebViewBridgePackage() //<- this
        );
    }
  1. add the following codes to your android/setting.gradle

you might have multiple 3rd party libraries, make sure that you don't create multiple include.

include ':app', ':react-native-webview-bridge'
project(':react-native-webview-bridge').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-webview-bridge/android')
  1. edit android/app/build.gradle and add the following line inside dependencies
compile project(':react-native-webview-bridge')
  1. run react-native run-android to see if everything is compilable.

Usage

just import the module with one of your choices way:

** CommonJS style **

var WebViewBridge = require('react-native-webview-bridge');

** ES6/ES2015 style **

import WebViewBridge from 'react-native-webview-bridge';

WebViewBridge is an extension of WebView. It injects special script into any pages once it loads. Also it extends the functionality of WebView by adding 1 new method and 1 new props.

sendToBridge(message)

the message must be in string. because this is the only way to send data back and forth between native and webview.

onBridgeMessage

this is a prop that needs to be a function. it will be called once a message is received from webview. The type of received message is also in string.

allowFileAccessFromFileURLs (Android only)

this is a prop that allows locally loaded pages via file:// to access other file:// resources. Pass-thru to corresponding setting in WebView. Default is false for Android 4.1 and above.

allowUniversalAccessFromFileURLs (Android only)

this is a prop that allows locally loaded pages via file:// to access resources in any origin. Pass-thru to corresponding setting in WebView. Default is false for Android 4.1 and above.

Bridge Script

bridge script is a special script which injects into all the webview. It automatically register a global variable called WebViewBridge. It has 2 optional methods to implement and one method to send message to native side.

send(message)

this method sends a message to native side. the message must be in string type or onError method will be called.

onMessage

this method needs to be implemented. it will be called once a message arrives from native side. The type of message is in string.

onError (iOS only)

this is an error reporting method. It will be called if there is an error happens during sending a message. It receives a error message in string type.

Notes

a special bridge script will be injected once the page is going to different URL. So you don't have to manage when it needs to be injected.

You can still pass your own javascript to be injected into webview. However, Bridge script will be injected first and then your custom script.

Simple Example

This example can be found in examples folder.

const injectScript = `
  (function () {
                    if (WebViewBridge) {

                      WebViewBridge.onMessage = function (message) {
                        if (message === "hello from react-native") {
                          WebViewBridge.send("got the message inside webview");
                        }
                      };
                
                      WebViewBridge.send("hello from webview");
                    }
                  }());
`;

var Sample2 = createReactClass({
  onBridgeMessage(message){
    const { webviewbridge } = this.refs;

    switch (message) {
      case "hello from webview":
        webviewbridge.sendToBridge("hello from react-native");
        break;
      case "got the message inside webview":
        console.log("we have got a message from webview! yeah");
        break;
    }
  },
  
  render() {
    return (
      <WebViewBridge
        ref="webviewbridge"
        onBridgeMessage={this.onBridgeMessage.bind(this)}
        injectedJavaScript={injectScript}
        source={{uri: "https://google.com"}}/>
    );
  }
});

More Repositories

1

example-react-native-redux

react native redux counter example
JavaScript
1,175
star
2

react-native-share-extension

react-native as an engine to drive share extension
Java
764
star
3

react-native-dropdown

This is simple implementation of drop down menu
JavaScript
658
star
4

react-native-tabbar

Tab bar with more freedom
JavaScript
265
star
5

Proton.js

Tiny framework for writing inheritance in javascript
JavaScript
77
star
6

ssh-scp-action

Github actions for executing commands and uploading files to remote server
Shell
27
star
7

react-native-2-side-menus

The 2 Side Menus
JavaScript
22
star
8

callbag.go

golang implementation of Callbag
Go
20
star
9

react-native-logger

Async aware logger for react-native with grouping and filter feature
JavaScript
20
star
10

react-native-swiss-knife

Implementation of Missing APIs in React-Native
Java
19
star
11

react-native-updater

an open source version of AppHub!
Objective-C
15
star
12

react-native-pure-icon

Using Pure JS for displaying icon
Objective-C
12
star
13

ecs

Entity Component System in golang
Go
11
star
14

scopejs

The world's smallest dependency injection framework
JavaScript
7
star
15

react-native-double-buffer

Simple React Native Double Buffer
JavaScript
5
star
16

parcel-ssr-code-splitting

Super minimum Parcel, SSR(Streaming) and Code Splitting
JavaScript
5
star
17

JSON-2-SQLite

Tiny program which import JSON structure into SQLite
C++
4
star
18

hlc

Hybrid Logical Clocks
Go
4
star
19

baker.go

yet another dynamic http reverse proxy
Go
4
star
20

react-native-scene-manager

Simple Scene Manager for React-Native, use https://github.com/pressly/scene-router instead
JavaScript
3
star
21

mobx-navigation

simplified the integration of mobx on top of react-navigation.
JavaScript
3
star
22

react-native-request

simple wrapper around fetch api to make it easier to work with
JavaScript
3
star
23

git-release-note

Git flow release note generator
JavaScript
3
star
24

elm-vector2d

a Vector2D implemantion for Elm
Elm
2
star
25

script.go

a Github Action to write everything in Go
Go
2
star
26

maat

a markdown table to typescript compiler for configuration files
TypeScript
2
star
27

Castify.js

A wrapper around ChromeCast sender apis for Chrome browser.
JavaScript
2
star
28

mark.js

Tiny/Open framework for managing dependencies in JavaScript
JavaScript
2
star
29

ali.js

a node base tool
JavaScript
2
star
30

gowrk

gowrk is a simple benchmark utility for testing webpages that redirect
Go
2
star
31

include.js

Light and Simple dependency manager in JavaScript.
JavaScript
2
star
32

crypto.go

Common Crypto functions in Go
Go
2
star
33

deamon.go

golang signal interrupt made easy
Go
1
star
34

configator

configator is a set of tools to deal with configuration files
TypeScript
1
star
35

dope-stream

chainable node.js stream api
TypeScript
1
star
36

baker

simple and extendable http reverse proxy
Go
1
star
37

complex

complex is a WebGL2 game
TypeScript
1
star
38

json

fast and simple JSON parser implementation
Java
1
star
39

react-native-dimensions

normalized dimensions in react-native
JavaScript
1
star
40

react-native-through2

through2 for react-native
JavaScript
1
star
41

trie-route

yet another router implementation with trie at core
JavaScript
1
star
42

store-repository

simple and powerful singleton management
JavaScript
1
star
43

example-side-menu-redux

Example of using Redux to Control Side Menu
JavaScript
1
star
44

conceal

a tool to encrypt and decrypt `string` and `[]byte` fields in struct
Go
1
star
45

zero

zero width chars to hide your information
Go
1
star
46

go-boggle

Boggle Solver in Golang
Go
1
star
47

fsm.go

a finite state machine in Golang
Go
1
star
48

react-ssr-performance

testing ssr streaming and static performance
JavaScript
1
star
49

goproto

go wrapper which compiles all proto files in your project
Go
1
star
50

pkg.go

my pkg.go
Go
1
star
51

ella

yet another IDL for generating proper RPC for golang client/server and other languages
Go
1
star
52

example-cli

an example of creating self-updating golang cli with step by step guide
Go
1
star