JavaScript Bridge Overview

The GoNative JavaScript Bridge is an API embedded in your app that allows your website to dynamically control and configure your app, and access the mobile device native functionality and hardware.

There are two ways to use the JavaScript Bridge. You can use the JavaScript Bridge Library which provides an abstraction layer and helper JavaScript functions or alternatively you can use the GoNative Protocol to access the JavaScript Bridge directly.

JavaScript Bridge Library

The GoNative JavaScript Bridge Library can be accessed from any page that is displayed within your app. The JavaScript Library source can be found as follows:

🚧

Calling Commands on Page Load

The JavaScript Bridge Library functions are not be available to be called until the library initializes within your app. To ensure the library is available add JavaScript Bridge commands that should be called on page load to a JavaScript function gonative_library_ready() defined on your webpage. For iOS this function will always be called consistently. For Android this function will be called based on network speed and connectivity, and the JavaScript size/complexity of your website - consider using the GoNative Protocol if any issues are experienced.

↔️GoNative JavaScript Bridge

// Set screen brightness to 80% and the statusbar styling as soon as page loads
function gonative_library_ready(){
  gonative.screen.setBrightness(0.8);

  gonative.statusbar.set({
    'style':'light',
    'color':'80ff0000',
    'overlay':true
  });
}

Promises

Some GoNative JavaScript Bridge commands return JavaScript promises which you can use as per your convenience. For example, the command gonative.auth.status() returns a promise which you can utilize as follows:

↔️GoNative JavaScript Bridge

async function exampleAwaitFunction() {
      var result = await gonative.auth.status();
        // *** your code ***
}

// or

function exampleThenFunction() {
    gonative.auth.status()
          .then(function (data) {
               // *** your code ***
          });
}

Example Commands

Below is a listing of example JavaScript Bridge commands available in the JavaScript Bridge Library. For more commands explore the rest of our documentation.

<!-- Example General Commands -->

gonative.share.sharePage(shareURL)  //Share GoNative About Page Test
gonative.share.sharePage()  //Share Current Page Test
gonative.registration.send(customData)  //Registration
gonative.share.downloadFile({url: 'https://yoursite.com/file.pdf'})  //Download file
gonative.sidebar.setItems()  //Sidebar Empty
gonative.sidebar.setItems(sidebarItems)  //Sidebar Test
gonative.tabNavigation.setTabs(tabItems)  //Set Tabs
gonative.tabNavigation.selectTab(2)  //Select Tab 3
gonative.open.appSettings()  //Open Settings
gonative.webview.clearCache()  //Clear Webview Cache
gonative.navigationTitles.set(navTitle)  //Set Navigation title
gonative.navigationTitles.setCurrent({title: 'Title Text'})  //Set Current Nav Title
gonative.navigationTitles.revert()  //Revert Nav Titles to appConfig entries
gonative.navigationLevels.set(navLevel)  //Set Navigation Levels
gonative.navigationLevels.setCurrent(navLevelCurrent)  //Set Current Nav Level
gonative.navigationLevels.revert()  //Revert Nav Levels to appConfig entries
gonative.statusbar.set(statusBarStyle)  //Set Status Bar Styling
gonative.screen.setBrightness({brightness: 0.8, restoreOnNavigation: true})  //Set Brightness to 80% & Restore On Navigation
gonative.screen.setBrightness(0.8)  //Set Brightness to 80%
gonative.screen.setBrightness({brightness: 'default'})  //Set Default Brightness
gonative.navigationMaxWindows.set(3)  //Set Navigation Max Windows to 3
gonative.navigationMaxWindows.setCurrent(2)  //Set Current Navigation Max Windows to 2
gonative.connectivity.get({'callback':'connectivityStatusCallback'})  //Connectivity Get - Name
gonative.connectivity.get({'callback':connectivityStatusCallback})  //Connectivity Get - Function
gonative.connectivity.subscribe({'callback':'connectivityStatusCallback'})  //Connectivity Subscribe
gonative.connectivity.unsubscribe()  //Connectivity Unsubscribe
<!-- Example iOS Exclusive Commands -->

gonative.ios.window.open('https:  //gonative.io/about')  //iOS - Open About URL
gonative.ios.geoLocation.requestLocation()  //iOS - GeolocationShim Request Location
gonative.ios.geoLocation.startWatchingLocation()  //iOS - GeolocationShim Start Watching Location
gonative.ios.geoLocation.stopWatchingLocation()  //iOS - GeolocationShim Stop Watching Location
gonative.ios.attconsent.request({'callback': 'attconsentCallback'})  //iOS ATT Consent Request
gonative.ios.attconsent.status({'callback': 'attconsentCallback'})  //iOS ATT Consent Status - Name
gonative.ios.attconsent.status({'callback': attconsentCallback})  //iOS ATT Consent Status - Function
gonative.ios.backgroundAudio.start()  //iOS Background Audio Start
gonative.ios.backgroundAudio.end()  //iOS Background Audio End
<!-- Example Android Exclusive Commands -->

gonative.android.geoLocation.promptAndroidLocationServices()  //Android - Geolocation Request Location
gonative.android.screen.fullscreen()  //Android - Full Screen Mode
gonative.android.screen.normal()  //Android - Normal Mode
gonative.android.screen.keepScreenOn()  //Android - Keep Screen ON
gonative.android.screen.keepScreenNormal()  //Android - Keep Screen Normal
gonative.android.audio.requestFocus(true)  //Android - Request Audio focus
<!-- Example Native Plugin Commands -->

<!-- OneSignal Push Notifications -->

gonative.run.deviceInfo()  //Device Info
gonative.run.onesignalInfo()  //OneSignal Info

<!-- Facebook App Events -->

gonative.facebook.events.send(facebookData)  //Send facebook Data
gonative.facebook.events.sendPurchase(facebookPurchaseData)  //Send facebook Purchase Data

<!-- QR / Barcode Scanner -->
gonative.barcode.scan({'callback': barcodeScanner})  //Barcode Scanner

<!-- Google AdMob Native Ads -->
gonative.admob.showInterstitialIfReady()  //Admob - Show Interstitial If Ready
gonative.admob.showInterstitialOnNextPageLoadIfReady()  //Admob - Show Interstitial On Next Page Load If Ready
gonative.admob.banner.enable()  //Admob - Enable Banner
gonative.admob.banner.disable()  //Admob - Disable Banner
gonative.admob.request.tracking({'callback': trackingCallback})  //Admob - Request Tracking Consent

Accessing the GoNative JavaScript Bridge Library from your web application

🚧

Web Development Frameworks

When developing frontend code using frameworks such as Angular, React, Vue, etc you may not be able to access the gonative object and gonative.module.function() as listed above.

Option 1: Try accessing the functions explicitly as window.gonative.module.function().
Option 2: Embed the GoNativeJSBridgeLibrary.js file directly into your web project rather than relying on the native app to provide this code, see below for further details.
Option 3: Use the GoNative Protocol which does not require JavaScript, again see further below for details

Embedding GoNativeJSBridgeLibrary.js within a web application

  1. Start with a local version of the iOS GoNativeJSBridgeLibrary.js file.

  2. Make the following change to the addCommand function within the file to ensure compatibility with both iOS and Android. Do not make any changes to the other functions within the file.

function addCommand(command, params, persistCallback){
    var commandObject = undefined;
    if(params) {
        commandObject = {};
        if(params.callback && typeof params.callback === 'function'){
            params.callback = addCallbackFunction(params.callback, persistCallback);
        }
        if(params.callbackFunction && typeof params.callbackFunction === 'function'){
            params.callbackFunction = addCallbackFunction(params.callbackFunction, persistCallback);
        }
        if(params.statuscallback && typeof params.statuscallback === 'function'){
            params.statuscallback = addCallbackFunction(params.statuscallback, persistCallback);
        }
        commandObject.gonativeCommand = command;
        commandObject.data = params;
    } else commandObject = command;
  
    // Begin changes
    // 1. Comment out or delete the following iOS specific method
    // window.webkit.messageHandlers.JSBridge.postMessage(commandObject);

    // 2. Add the following to provide compatibility for both iOS and Android
    if(navigator.vendor === 'Apple Computer, Inc.'){
        window.webkit.messageHandlers.JSBridge.postMessage(commandObject);
    }
    else {
        if(params) commandObject = JSON.stringify(commandObject);
        JSBridge.postMessage(commandObject);
    }
    // End of changes
}

  1. Add the JavaScript Library functions for any active native plugins from your app source code. For iOS these are found under the OneSignalPlugin Pod in the js folder and for Android under plugins/oneSignal/src/main/assets.

GoNative Protocol

GoNative JavaScript Bridge commands can also be called using the gonative:// protocol handler. This is a lower level interface that does not depend on the JavaScript Bridge Library discussed above.

HTML

For simple commands you may use a standard html anchor element to define href:

↔️GoNative JavaScript Bridge

<a href="gonative://module/command?parameter=true">
  Run JavaScript Bridge Function
</a>

JavaScript Functions

For more complex commands you can use JavaScript to set window.location.href.

↔️GoNative JavaScript Bridge

if(navigator.userAgent.indexOf('gonative') > -1) {
  var json = JSON.stringify({
      active: true,
      titles: [{
        title: 'my title',
        regex: '.*'
     }]
  });
  window.location.href = 'gonative://navigationTitles/set?persist=true&data=' + encodeURIComponent(json);
}

Note that parameters that are JSON or text with special characters (e.g. URLs) must be encoded using encodeURIComponent().

↔️GoNative JavaScript Bridge

function shareAnyLink(url){
  if(navigator.userAgent.indexOf('gonative') > -1) {
    window.location.href = 'gonative://share/sharePage?url=' + encodeURIComponent(url);
  }
}

function shareSpecificLink(){
  if(navigator.userAgent.indexOf('gonative') > -1) {
    window.location.href = 'gonative://share/sharePage?url=https%3A%2F%2Fexample.com';
  }
}

Chaining Multiple Commands

Multiple simultaneous calls to the GoNative JavaScript Bridge protocol handler via your website JavaScript code will result in only the last command being executed. A simple solution is to include a 500ms delay between calls. However, our recommended solution is to use the gonative://nativebridge/multi command to chain multiple commands together.

↔️GoNative JavaScript Bridge

var urls = ['gonative://firstcommand/...', 'gonative://secondcommand/...'];
var json = JSON.stringify({urls: urls});
window.location.href = 'gonative://nativebridge/multi?data=' + encodeURIComponent(json);