React Native Webview with Javascript Bridge

Overview

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"}}/>
    );
  }
});
Issues
  • Moving the webview brigde to React-Native Core

    Moving the webview brigde to React-Native Core

    Hello guys,

    I have decided that, it is time to move this project into core. one of the problem with maintaining this project is not be able to extend the native class and as a result I have to copy and paste the entire source code of WebView implementation of react-native. This makes it very difficult. So what I'm asking is goto this link and vote that one. If I get the confirmation from core-team I will make a PR request to WebView and I will merge this project to core.

    opened by alinz 94
  • Tracking: Upgrade to react-native@0.8

    Tracking: Upgrade to [email protected]

    It would be nice to be able to upgrade to [email protected] I'm opening this to track the issue, and potentially investigate fixes.

    There is an issue filed in the react-native project at: https://github.com/facebook/react-native/issues/2010

    In the meantime, we may be able to implement a retry workaround. @lightsofapollo commented there with,

    Okay after a minimum of digging it turns out that it's a fairly simple race... It looks like pre 0.7 attempting to access viewRegistry for a particular reactTag was more deterministic (or the race was smaller) ... In my case I wrap my access to viewRegistry in a retry (which itself is only called in addUIBlock blocks).

    opened by KevinGrandon 24
  • [Android] injectScript not work

    [Android] injectScript not work

    https://github.com/alinz/react-native-webview-bridge/issues/69

    hi,Alinz,I also can't deal with it,need your help ,thanks

    opened by qq326646683 22
  • Android support

    Android support

    I've completed Android support in my fork of this project: https://github.com/jjshammas/react-native-webview-bridge

    Haven't had time to bring myself up-to-date with yours but feel free to take from mine if you have plans to work on Android.

    opened by jjshammas 15
  • [Android] injectScript not work!

    [Android] injectScript not work!

    I write bellow code:

    function webViewBridgeReady(cb) { if (window.WebViewBridge) { cb(window.WebViewBridge); return; }

    function handler() {
      document.removeEventListener('WebViewBridge', handler, false);
      cb(window.WebViewBridge);
    }
    document.addEventListener('WebViewBridge', handler, false);
    

    }

    function goDetail(id) { WebViewBridge.send("jump:" + id); }

    webViewBridgeReady(function (webViewBridge) { webViewBridge.send("message from webview"); });

    the html is get from server, html have a button and click to invoke the goDetail function,but in android the log cat say 'goDetail is not defined'. can you help me?

    opened by peng051410 15
  • Undo assumption that ViewManager will only handle a single WebView ever

    Undo assumption that ViewManager will only handle a single WebView ever

    See issue #105 for the specifics, basically WebViewBridgeManager assumed only one WebView-instance would exist in it's own lifecycle, which is apparently not quite true.

    Oh, and I fixed a potential nullpointerexception on the way, as Android Studio was nagging me about it. I assumed returning always returning a filled commandMap was prefered over returning null when the parent returns null.

    I wrote the contents of this PR in work time at Athom, a Netherlands-based startup.

    opened by goldenice 13
  • RCTViewManager   RCTView

    RCTViewManager RCTView

    image

    opened by zhangrundong 13
  • stops working after first time

    stops working after first time

    Hi, I am using this component and I love it, but i noticed a very wired thing. On the first time i go on a view that uses the bridge it works perfectly, but then after exploring the app and going into another view that uses the bridge it just won't work.

    I use the bridge to open links in browser, while I'm on 'Debug with Chrome' mode it works perfectly, but when I'm not in debug mode it just starts making problems.

    here is the code I'm injecting to the html:

    var linker = function() {
      var links = document.getElementsByTagName('a');
      for(var i=0, length=links.length; i<length; i++) {
        links[i].onclick = function(e){
          e.preventDefault();
          window.WebViewBridge.send(this.href);
        };
      }
    };
    
    window.onload = function() {
      if (window.WebViewBridge) {
        linker()
      }
      else{
        document.addEventListener('WebViewBridge', linker, false);
      }
    };
    

    I am using react-native-route-flux, is it possible that it have something to do with moving between routes?

    Maybe it's something you should consider about the mound and unmount of the component. It seems that it won't work after the first time it gets unmounted.

    opened by kadosh1000 13
  • Crashes app while navigating webView pages from one to other

    Crashes app while navigating webView pages from one to other

    Hello,

    I am facing crash issue with webView Bridge. When I navigate to webViewBridge page and before loading that page click on back button my app is crashing. When I send quick messages from webView to react native its crashing too (with backspace - deleting content from webview textarea and sending content to react native on change).

    Most of cases app is stuck into below line: "" RCTLogMustFix(@"Invalid view returned from registry, expecting RKWebView, got: %@", view); ""

    Full fucntion from file:

    RCT_EXPORT_METHOD(callbackCleanup:(nonnull NSNumber *)reactTag) { [self.bridge.uiManager addUIBlock:^(RCTUIManager *uiManager, RCTSparseArray *viewRegistry) { RCTWebView *view = viewRegistry[reactTag]; if (![view isKindOfClass:[RCTWebView class]]) { RCTLogMustFix(@"Invalid view returned from registry, expecting RKWebView, got: %@", view); }

    [view callbackCleanup:reactTag];
    

    }]; }

    Thanks in advance.

    opened by tazmattaz 11
  • fix Uncaught ReferenceError: WebViewBridgeAndroid is not defined

    fix Uncaught ReferenceError: WebViewBridgeAndroid is not defined

    fix bug: #71

    [INFO:CONSOLE(1)] "Uncaught ReferenceError: WebViewBridgeAndroid is not
    defined", source: (1)
    
    opened by magicismight 11
  • Bump ua-parser-js from 0.7.17 to 0.7.28

    Bump ua-parser-js from 0.7.17 to 0.7.28

    Bumps ua-parser-js from 0.7.17 to 0.7.28.

    Commits
    • 1d3c98a Revert breaking fix #279 and release as 0.7.28
    • 535f11b Delete redundant code
    • 642c039 Fix #492 LG TV WebOS detection
    • 3edacdd Merge branch 'master' into develop
    • acc0b91 Update contributor list
    • f726dcd Merge branch 'master' into develop
    • 383ca58 More test for tablet devices
    • 7c8aa43 Minor rearrangement
    • 09aa910 Add new device & browser: Tesla
    • 557cc21 More test for latest phones with unique form factor (fold/flip/qwerty/swivel)
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
  •  Could not find method compile() for arguments [project ':react-native-webview-bridge']

    Could not find method compile() for arguments [project ':react-native-webview-bridge']

    I am using react-native v0.6 and I have followed the installation steps but I am still facing this error any help?

    opened by LameesMahmoud97 1
  • WebView IOS error

    WebView IOS error

    Undefined symbols for architecture x86_64: "_RCTJSNavigationScheme", referenced from: -[RCTWebViewBridge webView:shouldStartLoadWithRequest:navigationType:] in libreact-native-webview-bridge.a(RCTWebViewBridge.o) -[RCTWebViewBridgeManager constantsToExport] in libreact-native-webview-bridge.a(RCTWebViewBridgeManager.o) ld: symbol(s) not found for architecture x86_64

    opened by zhdishaq 2
  • Update to WKWebView for iOS

    Update to WKWebView for iOS

    Since UIWebView is deprecated and cannot upload build from December 2020, Is it possible to update this library as it uses WKWebView?

    opened by Rejsal 0
  • WebView has been removed

    WebView has been removed

    I'm just trying to get a basic webview working with no additional logic and after installation and following the README directions for iOS i get the following errors:

    Screen Shot 2020-01-29 at 9 08 14 PM

    opened by dancnnm 3
  • android app crash while run the app

    android app crash while run the app

    Get run time error and app will be crash. E/AndroidRuntime: FATAL EXCEPTION: mqt_native_modules Process: com.textediter, PID: 6385 java.lang.NoClassDefFoundError: com.github.alinz.reactnativewebviewbridge.WebViewBridgeManager at com.github.alinz.reactnativewebviewbridge.WebViewBridgePackage.createViewManagers(WebViewBridgePackage.java:21) at com.facebook.react.ReactInstanceManager.getOrCreateViewManagers(ReactInstanceManager.java:782) at com.facebook.react.CoreModulesPackage.createUIManager(CoreModulesPackage.java:184) at com.facebook.react.CoreModulesPackage.getModule(CoreModulesPackage.java:152) at com.facebook.react.TurboReactPackage$ModuleHolderProvider.get(TurboReactPackage.java:122) at com.facebook.react.TurboReactPackage$ModuleHolderProvider.get(TurboReactPackage.java:110) at com.facebook.react.bridge.ModuleHolder.create(ModuleHolder.java:188) at com.facebook.react.bridge.ModuleHolder.getModule(ModuleHolder.java:153) at com.facebook.react.bridge.NativeModuleRegistry.getModule(NativeModuleRegistry.java:148) at com.facebook.react.bridge.CatalystInstanceImpl.getNativeModule(CatalystInstanceImpl.java:479) at com.facebook.react.bridge.CatalystInstanceImpl.getNativeModule(CatalystInstanceImpl.java:466) at com.facebook.react.uimanager.UIManagerHelper.getUIManager(UIManagerHelper.java:31) at com.facebook.react.ReactInstanceManager.attachRootViewToInstance(ReactInstanceManager.java:1054) at com.facebook.react.ReactInstanceManager.setupReactContext(ReactInstanceManager.java:1012) at com.facebook.react.ReactInstanceManager.access$1400(ReactInstanceManager.java:125) at com.facebook.react.ReactInstanceManager$5$2.run(ReactInstanceManager.java:972) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:26) at android.os.Looper.loop(Looper.java:148) at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:225) at java.lang.Thread.run(Thread.java:818)

    opened by lalakiyarahul66 8
  • Is this repo officially inactive ?

    Is this repo officially inactive ?

    In react native version 0.60, this library does not seem to work, since react native moved webview from the core in to a separate repo.

    Are there any plans to upgrade this library aswell?

    opened by adkaushik 2
  • onBridgeMessage method not working

    onBridgeMessage method not working

    onBridgeMessage method not working in Android,worked in iOS

    opened by aneena-thomas 0
  • Not working with react-native 0.6

    Not working with react-native 0.6

    Since react-native v0.6 they have separated the WebView from the core product and needs to be included from the react native community -> https://github.com/react-native-community/react-native-webview instead.

    It would be super nice if this could be supported in a new release :)

    opened by CeciliaFredriksson 3
  • 'React/RCTViewManager.h' file not found

    'React/RCTViewManager.h' file not found

    "react-native": "0.57.8",

    x-code: 10.2.1

    I got this when I try to add "react-native-zss-rich-text-editor"

    it needs to add the native react-native-webview-bridge-updated dependency

    opened by mahalo777 1
Releases(v0.40.1)
Owner
Ali Najafizadeh
a gopher who understand React and React-Native ¯\_(ツ)_/¯
Ali Najafizadeh
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

Jordan Sexton 93 Aug 9, 2021
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

Nixon 182 Oct 11, 2021
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

Naoufal Kadhom 485 Sep 28, 2021
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

PrestoDoctor 127 Mar 14, 2021
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

KodersLab 251 Jun 30, 2021
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

null 10 Sep 28, 2021