JavaScript Bridge Overview

The Median 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 Median Protocol to access the JavaScript Bridge directly.

👍

GoNative → Median Transition

For existing apps that were last updated on the GoNative.io platform you must use gonative rather than median. For example gonative.statusbar.set() or gonative://statusbar/set.

For apps that have been updated on Median.co you may use either gonative or median.

JavaScript Bridge Library

The Median JavaScript Bridge Library is injected into your webpage DOM at runtime and can be accessed from any page that is displayed within your app. The JavaScript Library source can be found as follows:

  • iOS core app: LeanIOS/GoNativeJSBridgeLibrary.js
  • iOS native plugins: Within Pods/pluginName/js
  • Android: app/src/main/assets/GoNativeJSBridgeLibrary.js
  • Android native plugins: Within plugins/pluginName/src/main/assets

We also provide a JavaScript Bridge NPM Package to simplify usage within web frameworks such as React.

👍

Developer Demo

Display our demo page in your app to test during development https://median.dev/library-ready/

Calling Commands on Page Load

🚧

Calling Commands on Page Load

The JavaScript Bridge Library functions are not be available to be called until the library initializes within your app. Any JavaScript Bridge commands that should be called on page load can be added to a JavaScript function median_library_ready() defined on your webpage that is called after initialization. Alternatively you may use the Median Protocol so that you are not reliant on the JavaScript Bridge Library.

↔️Median JavaScript Bridge

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

  // Set status bar to light mode, red color, with overlay
  median.statusbar.set({
    'style':'light',
    'color':'80ff0000',
    'overlay':true
  });
  
  //Or dynamically set status bar using our helper function
  median_match_statusbar_to_body_background_color();
}

median_library_ready() is not called by your app

🚧

Ensure median_library_ready is available to be called by your app

Typically the JavaScript Bridge Library is initialized after your web content loads. However, if the median_library_ready() function is not being called within your app this indicates the library is initializing before your web content loads and before the median_library_ready() function is defined, resulting in a function misfire. To solve this add the below code to call the function manually if the JavaScript Bridge Library is initialized and available.

↔️Median JavaScript Bridge

function median_library_ready(){
 // Your code here 
}

// Call the function manually if your page content is slow to load and
// expose the median_library_ready() function, e.g. using a web framework
if(window.median){
	window.median_library_ready();
}

Promises

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

↔️Median JavaScript Bridge

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

// or

function exampleThenFunction() {
    median.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 -->

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

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

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

<!-- OneSignal Push Notifications -->

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

<!-- Facebook App Events -->

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

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

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

Accessing the Median JavaScript Bridge Library from your web application

🚧

Web Development Frameworks

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

Option 1: Try accessing the functions explicitly as window.median.module.function().
Option 2: Import the Median JavaScript Bridge NPM Package into your project.
Option 3: Use the Median Protocol which does not require JavaScript. See further below for details.

If you are using on page callbacks you will need to ensure the function is exposed to global scope so that it can be used outside of your application bundle, e.g. window.callback_function = () => { }; or if using the NPM Package make use of listeners.

Median Protocol

Median JavaScript Bridge commands can also be called using the median:// 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:

↔️Median JavaScript Bridge

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

JavaScript Functions

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

↔️Median JavaScript Bridge

if(navigator.userAgent.indexOf('median') > -1) {
  var json = JSON.stringify({
      active: true,
      titles: [{
        title: 'my title',
        regex: '.*'
     }]
  });
  window.location.href = 'median://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().

↔️Median JavaScript Bridge

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

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

Chaining Multiple Commands

Multiple simultaneous calls to the Median 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 median://nativebridge/multi command to chain multiple commands together.

↔️Median JavaScript Bridge

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