React Native Webview with Javascript Bridge

Last update: Jun 17, 2022

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"}}/>
    );
  }
});

GitHub

https://github.com/alinz/react-native-webview-bridge
Comments
  • 1. 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.

    Reviewed by alinz at 2016-06-23 16:27
  • 2. 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).

    Reviewed by KevinGrandon at 2015-07-24 20:09
  • 3. [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?

    Reviewed by peng051410 at 2016-03-03 08:10
  • 4. 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.

    Reviewed by jjshammas at 2015-12-15 21:21
  • 5. 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.

    Reviewed by goldenice at 2016-06-20 11:06
  • 6. 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.

    Reviewed by kadosh1000 at 2016-02-27 01:25
  • 7. 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.

    Reviewed by tazmattaz at 2015-09-01 12:01
  • 8. WebViewBridge bug??

    2016-09-21 2 37 41 My HTML:
    imgs[i].onclick=function(){ alert(1); WebViewBridge.send('a'); alert(2); } only alert 1,cannot alert 2; I think WebViewBridge is undefind. This error appears after update XCode8

    Reviewed by camellieeee at 2016-09-21 06:46
  • 9. Send message from webview's page to the app

    Is there a way to send data from the HTML to the page when the user taps on a button or something in the webview?

    What I'm looking for is basically the equivalent of this library that I can embed in the webpage which would send a value to the app on its terms, not page load.

    Reviewed by Naoto-Ida at 2016-06-29 07:46
  • 10. NSUnknownKeyException

    I get this error just by instantiating the WebViewBridge. The full error is:

    2015-10-16 20:24:11.076 iphoneDEV[84420:4635019] *** WebKit discarded an uncaught exception in the webView:decidePolicyForNavigationAction:request:frame:decisionListener: delegate: [<RCTWebView 0x7fd3ec0e4750> valueForUndefinedKey:]: this class is not key value coding-compliant for the key _eventDispatcher.

    After digging around a bit I don't think that WebKit has actually anything to do with it. But I have no idea where this could come from.

    I'm using react-native 0.13.0-rc

    Reviewed by d-vine at 2015-10-17 00:33
  • 11. WebViewExManager.NavigationType error when starting project

    Hi @alinz - I'm seeing some errors when trying to use this project, and I was wondering if you had any ideas.

    2015-06-30 14:19:56.194 [error][tid:com.facebook.React.JavaScript] "Error: undefined is not an object (evaluating 'WebViewExManager.NavigationType') stack: index.ios.bundle:43155 require index.ios.bundle:244 index.ios.bundle:42219 require index.ios.bundle:244 index.ios.bundle:1110 require index.ios.bundle:244 applyWithGuard index.ios.bundle:880 require index.ios.bundle:195 index.ios.bundle:43383 URL: http://localhost:8081/index.ios.bundle line: 43155

    message: undefined is not an object (evaluating 'WebViewExManager.NavigationType')" 2015-06-30 14:19:56.245 [info][tid:com.facebook.React.JavaScript] "Running application "MyApp" with appParams: {"rootTag":1,"initialProps":{}}. DEV === true, development-level warning are ON, performance optimizations are OFF"

    Reviewed by KevinGrandon at 2015-06-30 21:24
  • 12. 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.

    Reviewed by dependabot[bot] at 2021-05-07 00:56
  • 13. 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

    Reviewed by zhdishaq at 2020-05-25 18:11
  • 14. 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

    Reviewed by dancnnm at 2020-01-30 02:09
  • 15. 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)

    Reviewed by lalakiyarahul66 at 2019-12-14 06:26
  • 16. 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?

    Reviewed by adkaushik at 2019-10-31 10:43
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 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
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
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
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
Simple React Native Android module to use Android's WebView inside your app
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

May 8, 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 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
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
Snoopy is a profiling tool for React Native, that lets you snoop on the React Native Bridge.
Snoopy is a profiling tool for React Native, that lets you snoop on the React Native Bridge.

React Native Snoopy UPDATE: I wrote an article with the story behind this library. Snoopy is a profiling tool for React Native, that lets you snoop on

May 30, 2022
React Native Bridge for Native Spruce Animation Library
React Native Bridge for Native Spruce Animation Library

ReactNative Spruce - (Android & iOS): Deprecated Due to time constraint, this library is deprecated and not maintained anymore, You can still use thi

May 17, 2022
React Native bridge for gtk desktop applications
React Native bridge for gtk desktop applications

react-gtk cross-platform react native desktop applications Please ★ this repo if you found it useful ★ ★ ★ Built with Node GTK Built by Silicon Hills

Jun 5, 2022
React native bridge for AppAuth - an SDK for communicating with OAuth2 providers
React native bridge for AppAuth - an SDK for communicating with OAuth2 providers

React Native App Auth React native bridge for AppAuth - an SDK for communicating with OAuth2 providers This versions supports [email protected]+. The

Jun 24, 2022
A cross-platform bridge that allows you to enable and disable the screen idle timer in your React Native app

react-native-idle-timer A cross-platform bridge that allows you to enable and disable the screen idle timer in your React Native app Install npm insta

May 23, 2022
React Native Bridge for ADBannerView – DEPRECATED
React Native Bridge for ADBannerView – DEPRECATED

react-native-adbannerview [DEPRECATED] This component serves as a bridge for ADBannerview. Feel free to contribute :-) Installation npm install react-

May 31, 2020
React Native module bridge to iOS MFMessageComposeViewController

08/01/2017 - This project is no longer actively maintained. It will remain here so it can still be used but there will be no further updates or bug fi

Oct 4, 2021
React Native module bridge to obtain information about the user’s home cellular service provider,

React Native Carrier Info React Native module bridge to obtain information about the user’s home cellular service provider. Makes use of the following

Jun 12, 2022