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 thanmedian
. For examplegonative.statusbar.set()
orgonative://statusbar/set
.For apps that have been updated on Median.co you may use either
gonative
ormedian
.
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.
Developer Demo
Display our demo page in your app to test during development https://median.dev/library-ready/
The JavaScript Bridge 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 NPM Package to simplify usage within web frameworks such as React. When using the NPM Package you are not dependant on the app to inject the library and should toggle the option to prevent the injection on the Website Overrides tab within the App Studio.
Median
notmedian
when using NPM packageWhen using the NPM Package make note to use capitalized
Median
to call functions rather than lowercasemedian
which is reserved for the the injected JavaScript library. Your IDE should be configured to help with code hinting to help with completion and avoid semantic errors.
Calling Commands on Page Load
Calling Commands on Page Load
The JavaScript Bridge Library functions are not 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
median_library_ready()
is not called by your appEnsure
median_library_ready
is available to be called by your appTypically 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 themedian_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 handle as needed, including managing errors. For example, the command median.iap.purchase()
returns a promise that can be used as follows:
↔️Median JavaScript Bridge
async function exampleAwaitFunction() { try { const purchasesData = await median.iap.purchase({ 'productID': 'product_id' }); console.log(purchasesData); // *** Your code to handle the purchase *** } catch (error) { console.log(error); // *** Your code to handle errors *** } } // or function exampleThenFunction() { median.iap.purchase({ 'productID': 'product_id' }) .then(function(purchasesData) { console.log(purchasesData); // *** Your code to handle the purchase *** }) .catch(function(error) { console.log(error); // *** Your code to handle errors *** }); }
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 andmedian.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); }
Encoding Special Characters
Parameters that are JSON or text with special characters (e.g. URLs) must be encoded using encodeURIComponent()
.
Example for Prompt Share Dialogue:
↔️Median JavaScript Bridge
function shareSpecificLink(){ if(navigator.userAgent.indexOf('median') > -1) { window.location.href = 'median://share/sharePage?url=https%3A%2F%2Fexample.com'; } } function shareAnyLink(url){ if(navigator.userAgent.indexOf('median') > -1) { window.location.href = 'median://share/sharePage?url=' + encodeURIComponent(url); } } shareAnyLink('https://example/com');
Example for Link Behavior:
↔️Median JavaScript Bridge
function openSpecificUrl(){ if(navigator.userAgent.indexOf('median') > -1) { window.location.href = 'median://window/open?url=url=https%3A%2F%2Fexample.com&mode=appbrowser'; } } function openAnyUrl(url, mode){ if(navigator.userAgent.indexOf('median') > -1) { window.location.href = 'median://window/open?url=' + encodeURIComponent(url) + '&mode=' + mode; } } openAnyUrl('https://example/com','appbrowser');
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);
Updated about 1 month ago