Skip to content

Telefonica/webview-bridge

Repository files navigation

GitHub tag License CI status

JavaScript library to access to native functionality. Requires a webview with a postMessage bridge.

Library size ~1.2 Kb (min + gzip)

AMD, UMD, IIFE, ES Module builds available (see package dist folder). Open an issue if you need a different build.

Usage

NPM

We recommend to manage your dependencies using npm or yarn and use a bundler like webpack or parcel. Once configured, you can use ES imports.

Install using npm:

npm i @tef-novum/webview-bridge

Install using yarn:

yarn add @tef-novum/webview-bridge

Import required function and use it:

import {setWebViewTitle} from '@tef-novum/webview-bridge';

setWebViewTitle('Hello, world');

CDN

Alternatively, you can import the library directly from a CDN:

<script src="https://unpkg.com/@tef-novum/webview-bridge/dist/webview-bridge-iife.min.js"></script>

<script>
    webviewBridge.setWebViewTitle('Hello, world');
</script>

API

isWebViewBridgeAvailable

Available in B2P App version >=24.10

Returns true if WebView Bridge is available. Use this function to implement fallbacks in case the bridge is not available.

isWebViewBridgeAvailable: () => boolean;

Inside an iframe

By default, the bridge will be disabled inside an iframe. If you want to enable it, add a data-enable-webview-bridge attribute to the host iframe element.

Example

if (isWebViewBridgeAvailable()) {
    nativeAlert('Hello'); // use bridge
} else {
    myCustomAlert('Hello'); // use alternative implementation
}

You may want to detect if the page is displayed inside a regular browser or an Android or iOS WebView.

/** Returns true if application is running inside a Novum App WebView */
const isWebView = () => isWebViewBridgeAvailable();

/** Returns true if application is running inside a Novum App WebView running on Android */
const isAndroidWebView = () =>
    isWebViewBridgeAvailable() && navigator.userAgent.includes('Android');

/** Returns true if application is running inside a Novum App WebView running on iOS */
const isIOSWebView = () =>
    isWebViewBridgeAvailable() && !navigator.userAgent.includes('Android');

requestContact

Show native picker UI in order to let the user select a contact.

  • Android only: picker UI elements can be filtered by available phones (default) or emails. filter property is ignored by iOS devices

requestContact: ({filter?: 'phone' | 'email'}) => Promise<{
    name?: string;
    email?: string;
    phoneNumber?: string;
    address?: {
        street?: string;
        city?: string;
        country?: string;
        postalCode?: string;
    };
}>;

All fields in response object are optional

Example

requestContact({filter: 'phone'}).then((contact) => {
    console.log(contact);
}).catch(err => {
    console.error(err);
};

createCalendarEvent

Inserts an event in calendar

createCalendarEvent: ({
    beginTime: number,
    endTime: number,
    title: string
}) => Promise<void>;

beginTime and endTime are timestamps with millisecond precision

Example

createCalendarEvent({
    beginTime: new Date(2019, 10, 06).getTime(),
    endTime: new Date(2019, 10, 07).getTime(),
    title: "Peter's birthday",
}).then(() => {
    console.log('event created');
}).catch(err => {
    console.error(err);
};

share

App version >=10.7

Invokes the native sharing mechanism of the device.

type ShareOptions =
    | {
          text: string;
      }
    | {
          url: string;
          fileName: string;
          text?: string;
      };

share: (options: ShareOptions) => Promise<void>;
  • If no url is present, text is used as item to share
  • If url param is present, it contains the URL to the shared file
  • fileName param is mandatory if url is set
  • If url and text are set, text is used as Intent BODY (if platform allows it)

Example

// sharing a text string
share({text: 'Hello, world!'});

// sharing a file
share({url: 'https://path/to/file', fileName: 'lolcats.png'});

shareBase64

App version >=24.6

Invokes the native sharing mechanism of the device to share a file. The file is provided as a base64 encoded string.

shareBase64: ({contentInBase64: string; fileName: string}) => Promise<void>;
  • The file type will be inferred from the fileName extension.

Example

shareBase64({
    contentInBase64: 'SGVsbG8sIHd(...)vcmxkCg==',
    fileName: 'hello.pdf',
});

downloadBase64

App version >=24.10 App version >=24.9 in O2ES

Opens the provided file using the download webview mode. The file is provided as a base64 encoded string.

downloadBase64: ({contentInBase64: string; fileName: string}) => Promise<void>;
  • The file type will be inferred from the fileName extension. The file extension is mandatory. Take into account that iOS webview won't be able to render file types not supported by Safari.

Behaviour

Android
  1. Once file is correctly processed, a "Downloaded" notification is shown in the system notifications inbox. System will try to open the file when clicking on it.
  2. Simultaneously, app will try to open the given file, this may result in 3 situations:
    • No app that can handle this type of file is available
      • Nothing will happen, user feedback will be just the previous generated notification.
    • Multiple apps can handle this type of file
      • System will show a desambiguator window to select the app which will be used to open the file.
    • Single app can open this type of file (Or an app is set as default for these kind of files)
      • Downloaded content will be opened using the only available App that supports its extension.
base64_download.mp4
iOS

The behavior will be similar to the current webview download mode but downloading the file before showing it

1.- Once the file is correctly procesed, it will be stored in a tmp directory 2.- The app will open a modal webview presenting the local file in a web browser similar to the one used in download webview mode but hiding the "Open in Safari" button (due to no sense for a local file).

iOS_base64_download.MP4

Example

downloadBase64({
    contentInBase64: 'SGVsbG8sIHd(...)vcmxkCg==',
    fileName: 'hello.pdf',
});

updateNavigationBar

App version >= 10.7: Partial support
App version >= 11.8: expandedTitle
App version >= 14.8: Additional properties and deprecations
Partial support in B2P App version <=24.10: title
Partial support in B2P App version >=24.11: right actions
Full support in B2P App version >=24.12: title

Customize WebView NavigationBar properties. You can set one or more properties in a single call

type NavigationBarIcon = {
    /** Identifier. The native side will notify the WebView when the icon is clicked using this id*/
    id: string;
    /** URL to be opened by the app as a deep-link if present */
    url?: string;
    /** Content description of the image used for accessibility */
    name: string;
    /**
     * This is a string whose value will be mapped to a local resource that the app already knows.
     * See https://void.tuenti.io/idl-server/files/TopNavbarIcon/1.1 for available values.
     * A fallback icon will be used if the app doesn't recognize the value.
     */
    iconEnum?: string;
    /**
     * Set of urls that the app will use to render the icon.
     * If both iconEnum and icon are received, the iconEnum should be used as a fallback in case there's some issue with the urls.
     */
    icon?: {
        /**
         * Those urls should be icons in PNG format.
         * The icons will not be rendered until the image has been downloaded by the app.
         * The URLs should be inmutable to allow the app to cache those icons for an arbitrary amount of time.
         */
        url: string;
        /** To be used if present when dark mode is activated. */
        urlDark?: string;
    };
    badge?: {
        /**
         * Boolean to determine if the badge should be shown
         * If `show` is `true` and number and nativeLogic are not present, the badge will be shown as a dot
         */
        show: boolean;
        /** Same logic and current same supported values as in nativeLogic field from API */
        nativeLogic?: 'INBOX' | 'PROFILE';
        /** Hardcoded value to set as the badge count. It will have more priority than nativeLogic. */
        number?: number;
    };
    /**
     * Tracking properties to be sent to analytics when the icon is clicked.
     * These properties will be merged to the tracking event produced by the native side
     */
    trackingProperties?: Record<string, string>;
}

updateNavigationBar = ({
    title?: string;
    expandedTitle?: string;
    showBackButton?: boolean;
    showReloadButton?: boolean;
    showProfileButton?: boolean; // deprecated in app version >= 14.8
    backgroundColor?: string;
    leftActions?: ReadonlyArray<NavigationBarIcon>; // requires app version >= 14.8
    rightActions?: ReadonlyArray<NavigationBarIcon>; // requires app version >= 14.8
    colorVariant?: 'INVERSE' | 'REGULAR' | null; // requires app version >= 14.8
    resetToDefaultState?: boolean; // requires app version >= 14.8
}) => Promise<void>
  • title: updates NavigationBar title
  • expandedTitle: updates NavigationBar expandedTitle. If the value is an empty string, the expanded navigation bar will not be shown. Only available in native app versions >= 11.8
  • showBackButton: shows or hides back icon in NavigationBar. On android, in case window does not support showing a back button (currently internal with modal presentation, which shows an X) this flag is ignored, as in these cases back navigation is always performed with the native back button
  • showReloadButton: shows or hides NavigationBar Reload button
  • showProfileButton: DEPRECATED. New apps will ignore this field
  • backgroundColor: change NavigationBar background color, use a hex color string (for example: '#FF128A')
  • leftActions: array of icons to show in the left side
  • rightActions: array of icons to show in the right side
  • colorVariant: defines how the icons and the text of the top bar should be tinted. If null or unknown value is received, the initial colors set by the app or the last colorVariant set will be used
  • resetToDefaultState: This is a flag used to indicate that the appearance of the top bar should be restored to its original state. The other fields that may come in the same bridge call will be applied after the reset

Examples

// updates WebView NavigationBar title
updateNavigationBar({title: 'Hello, World!'});

// full featured example
updateNavigationBar({
    title: 'Hello',
    expandedTitle: 'Hello, World!',
    showBackButton: true,
    showReloadButton: false,
    backgroundColor: '#FF0000',
    leftActions: [
        {
            id: 'iconID',
            name: 'icon name',
            iconEnum: 'SOME_ICON',
            badge: {
                show: true,
                nativeLogic: 'INBOX',
            },
        },
    ],
    rightActions: [
        {
            id: 'iconID',
            name: 'icon name',
            iconEnum: 'icon enum value',
            icon: {
                url: 'https://path/to/icon',
                urlDark: 'https://path/to/icon/dark',
            },
            badge: {
                show: true,
                number: 1,
            },
        },
    ],
    resetToDefaultState: true,
    trackingProperties?: {'name': 'some icon clicked'},
});

onNavigationBarIconClicked

App version >=14.8

Listen to navigation bar icon clicks and execute a callback function

React example

React.useEffect(() => {
    const unsubscribe = onNavigationBarIconClicked(({id}) => {
        console.log(`Icon with id ${id} clicked`);
    });

    // Unsubscribe when the component is unmounted
    return () => {
        unsubscribe();
    };
}, []);

isABTestingAvailable

App version >=10.8

Returns true if A/B testing named with the key is available.

isABTestingAvailable: (key: string) => Promise<boolean>;

nativeConfirm

App version >=24.6 destructive support.

Show a native confirm dialog.

If the bridge is not present (eg. showing the page in browser), fallbacks to a browser confirm.

nativeConfirm: ({
    message: string;
    title?: string;
    acceptText: string;
    cancelText: string;
    destructive?: boolean;
}) => Promise<boolean>;

Example

nativeConfirm({
    title: 'Confirm',
    message: 'Send message?',
    acceptText: 'Yes',
    cancelText: 'No',
}).then((res) => {
    if (res) {
        console.log('message sent');
    }
});

nativeAlert

Available in B2P App version >=24.10

Show a native alert dialog.

If the bridge is not present (eg. showing the page in browser), fallbacks to a browser alert.

nativeAlert: ({
    message: string;
    title?: string;
    buttonText: string;
}) => Promise<void>;

nativeMessage

App version >=14.10 withDismiss, duration and action in response.

App version >=24.6 buttonAccessibilityLabel support.

Show a native snackbar message. Use it to display feedback messages.

If the bridge is not present (eg. showing the page in browser), fallbacks to a browser alert.

nativeMessage: ({
        message: string;
        duration?: 'PERSISTENT';
        buttonText?: string;
        buttonAccessibilityLabel?: string;
        type?: 'INFORMATIVE' | 'CRITICAL' | 'SUCCESS';
        withDismiss?: boolean;
}) => Promise<{
    action: 'DISMISS' | 'BUTTON' | 'TIMEOUT' | 'CONSECUTIVE';
}>;

Example

Show a native Snackbar with button

nativeMessage({
    message: 'Operation finished!',
    buttonText: 'Ok',
}).then((res) => {
    if (res.action === 'BUTTON') {
        console.log('Button clicked');
    }
    console.log('Snackbar closed');
});

logEvent

Log an event to firebase

logEvent: ({
    category: string; // Typically the object that was interacted with (e.g. 'Video')
    action: string; // The type of interaction (e.g. 'play')
    label?: string; // Useful for categorizing events (e.g. 'Fall Campaign')
    value?: number; // A numeric value associated with the event (e.g. 43)
}) => Promise<void>;

If you want to use new Google Analytics 4 event format you can use this method too:

logEvent: ({
    name: string; // The event name is mandatory
    [key: string]: any; // You can set any other event parameters
}, {
    sanitize?: boolean; // Whether to sanitize the event params, this only affects to FirebaseEvents. true by default.
}) => Promise<void>;

Example

logEvent({
    category: 'topup-flow',
    action: 'topup',
}).then(() => {
    console.log('event logged');
});

// Or with GA4 format
logEvent({
    name: 'user_interaction',
    component_type: 'primary_button',
    component_copy: 'topup',
}).then(() => {
    console.log('event logged');
});

About event params sanitization

By default, GA4 event params are sanitized. The sanitization consists of removing whitespaces and some special characters, lowercasing and trimming. This allows us having a consistent event format accross events.

In some cases you may want to disable this behavior. To do so, you can set the sanitize option to false:

logEvent(yourEvent, {sanitize: false});

setScreenName

Log the current screen name (or page name) to firebase

setScreenName: (screenName: string, params?: {[key: string]: any}) => Promise<void>;

setUserProperty

Set a user property to firebase

setUserProperty: (name: string, value: string) => Promise<void>;

reportStatus

App version >=11.2

Report a given feature status

reportStatus: ({feature: 'ACCOUNT', status: 'CRITICAL' | 'GOOD' | 'BAD', reason: string}) => Promise<void>;

onNativeEvent

App version >=11.3

Listens to native app events

type NativeEventHandler = ({ event }: {event: string}) => {action: 'default'};

onNativeEvent: (handler: NativeEventHandler) => () => void;

Example

onNativeEvent(({event}) => {
    if (event === 'tappedNavigationBarBackButton') {
        // do something
    }
    return {action: 'default'};
});

Available events

  • tappedNavigationBarBackButton: fired when the user taps on the back button of the native Navigation Bar. Allowed response actions: default

checkPermissionStatus

App version >=11.4

Returns true if the app has the specific notifications permissions. You have to pass feature and required params for this request.

Avalaible features:

  • notifications
  • read-contacts (Available for app versions 13.10 and higher)
  • write-contacts (Available for app versions 13.10 and higher)
checkPermissionStatus: (feature: string, params?: {[key: string]: string}) => Promise<boolean>;

Example

checkPermissionStatus('notifications', {channelId: 'default'}).then(
    (hasPermissions) => {
        console.log(hasPermissions);
    },
);

internalNavigation

App version >=11.4

Init an internal and native navigation to a device specific feature

Avalaible features:

  • notification-settings
  • contact-settings App version >=13.10
internalNavigation: (feature: string) => Promise<void>;

dismiss

App version >=11.5

Dismiss the current webview and optionally navigate to another url

dismiss: (onCompletionUrl?: string) => Promise<void>;

requestVibration

Requests the phone to vibrate. Options are 'error' or 'success'.

requestVibration('error');

fetchContactsByPhone

Returns contacts info given an array of phone numbers.

fetchContactsByPhone: (phoneNumbers: Array<string>) => Promise<Array<{
    phoneNumber: string;
    firstName?: string;
    middleName?: string;
    lastName?: string;
    encodedAvatar?: string;
}>>;

getAppMetadata

App version >=11.8

Check if an app is installed in the phone

getAppMetadata: (appToken: string) => Promise<{
    isInstalled: boolean;
    marketUrl: string;
    appUrl: string
}>;
  • appToken: token that refers to a "friend" application
  • isInstalled: boolean to see if the app is installed
  • appUrl: string url to launch an app installed on the phone
  • marketUrl: string url to launch the store in a specific application

getDiskSpaceInfo

App version >=11.10

Return info about how much free disk space the device has

getDiskSpaceInfo: () => Promise<{availableBytes: number, totalBytes: number}>;
  • availableBytes: number to see available bytes in the device
  • totalBytes: number to see the total bytes in the device

getEsimInfo

App version >=12.3 supportsEsim
App version >=14.8 eid

Return info about the esim capabilities of the device

getEsimInfo: () => Promise<{supportsEsim: boolean, eid?: string | null}>;
  • supportsEsim: tells if the device supports esim
  • eid: "Embedded Identity Document". The serial number corresponding to the eSIM installed in a device.

getDeviceModel

App version >=14.8

Returns the device model, like "SAMSUNG-SM-G930A", "iPhone9", ...

getDeviceModel: () => Promise<{model: string} | null>;

setTrackingProperty

App version >=12.4

Sets a property related to some specific tracking system

setTrackingProperty: (system: 'palitagem' | 'medallia', name: string, value?: string) => Promise<void>;
  • system: Tracking system that will handle the property
  • name: name of the property
  • value: value of the property (nullable)

setActionBehavior

App version >=12.7

Method that allows defining an specific behavior (such as showing a confirmation) before the specific native actions are executed. This method also allows disabling any previous behaviors set.

type ActionBehavior =
    | {
        behavior: 'confirm';
        title: string;
        message: string;
        acceptText: string;
        cancelText: string;
    }
    | {
        behavior: 'default';
    }
    | {
        behavior: 'cancel';
    };

setActionBehavior: (actions: {webviewClose?: ActionBehavior, navigationBack?: ActionBehavior}) => Promise<void>;

navigationBack and webviewClose actions are currently available:

  • navigationBack: Action bar back button pressed (also for physical back button in android but not swipe back gesture in iOS, which will be disabled).
  • webviewClose: Action bar close button pressed. Includes both "X" and "Close" buttons (but not swipe down gesture in iOS, which will be disabled).

Both have same allowed json parameters, and 3 allowed behaviors:

  • confirm Show a confirmation dialog with the required title, message and buttons.
  • cancel Prevent action from being performed, just ignoring it.
  • default Set default behavior for the action. (Usually to reset any previously specified behavior).

Actions can be optionally included in the payload. Any not included action won’t change its current behavior set.

All actions behaviors will be automatically set to default on full page loads.

renewSession

Tell the app to renew the session.

renewSession = (
    oldAccessToken: string | null,
    options: {timeout?: number} = {},
) => Promise<string>

onSessionRenewed

Defines a callback that will be executed when the native app renews the session. Returns the unsubscribe function.

onSessionRenewed = (
    handler: (newAccessToken: string) => void,
) => (() => void)

logout

Available in B2P App version >=24.10

A method that requests a user logout.

logout = () => Promise<{success: boolean}>

getTopazToken

Returns the Topaz token.

getTopazToken = (options: {timeout?: number} = {}) => Promise<{token: string}>

getTopazValues

App version >=24.9

Returns an object containing values from the Topaz SDK.

getTopazValues = () => Promise<{syncId?: string}>

showAppRating

Available in B2P App version >=24.10

Show native app rating dialog

showAppRating = () => Promise<void>

bottomSheet

App version >=13.8

Show native bottom sheet UI

bottomSheet = (payload: SheetUI) => Promise<SheetResponse>
// see SheetUI and SheetResponse types

⚠️ If you try to call this method repeatedly while a sheet is already being opened (for example, user accidental double tap), it will throw an Error with code 423 (Locked)

There are some specific cases of bottom sheet, and we have some utility methods to make them simpler to use:

For single selection use bottomSheetSingleSelector:

bottomSheetSingleSelector = ({
    title?: string;
    subtitle?: string;
    description?: string;
    selectedId?: string;
    items: Array<SheetRowItem>;
}) => Promise<{action: 'SUBMIT' | 'DISMISS'; selectedId: string}>

For a bottom sheet with a list of actions use bottomSheetActionSelector:

bottomSheetActionSelector = ({
    title?: string;
    subtitle?: string;
    description?: string;
    items: Array<SheetActionItem>;
}) => Promise<{action: 'SUBMIT' | 'DISMISS'; selectedId: string}>

For an informative bottom sheet use bottomSheetInfo:

bottomSheetInfo = ({
    title?: string;
    subtitle?: string;
    description?: string;
    items: Array<SheetInfoItem>;
}) => Promise<void>

For a bottom sheet with ButtonPrimary/ButtonSecondary/ButtonLink use bottomSheetActions App version >=14.8:

bottomSheetActions = ({
    title?: string;
    subtitle?: string;
    description?: string;
    button: {
        text: string;
    };
    secondaryButton?: {
        text: string;
    };
    link?: {
        text: string;
        withChevron?: boolean;
    };
}) => Promise<{action: 'PRIMARY' | 'SECONDARY' | 'LINK' | 'DISMISS'}>

Example:

const {action, selected} = await bottomSheetSingleSelector({
    title: 'Some title',
    subtitle: 'Some subtitle',
    description: 'Some description',
    selectedId: 'item-1',
    items: [
        {
            id: 'item-0',
            title: 'item 0 title',
            description: 'item 0 description',
        },
        {
            id: 'item-1',
            title: 'item 1 title',
            description: 'item 1 description',
        },
        {
            id: 'item-2',
            title: 'item 2 title',
            description: 'item 2 description',
        },
    ],
});

fetchPhoneNumbers

App version >=13.10

Fetch all the phone numbers of the native phonebook

fetchPhoneNumbers:() => Promise<Array<{
    id: string;
    value: string;
}>>;

updatePhoneNumbers

App version >=13.10

Updates the given phone numbers in the native phonebook

updatePhoneNumbers:(Array<{
    id: string;
    value: string;
}>) => Promise<Void>;

highlightNavigationTab

Method that allows WebView to highlight a home tab bar setting a badge (numeric or not)

highlightNavigationTab: ({
    tab: string,
    highlight: boolean,
    count?: number
}) => Promise<void>;
  • If highlight is false: no badge is shown
  • If highlight is true:
    • If count is not null, it will show a numeric badge with countvalue
    • If count is null, it will show a non-numeric badge

getAttStatus

App version >=14.7 (iOS)

Method that allows a WebView to ask an iOS app user about the authorization status of his ATT (App Tracking Transparency) permission.

Resolves to null if the app is not running on iOS or if the method is not available

getAttStatus: () => Promise<{status:'granted' | 'denied' | 'unknown'} | null>;

getNetworkConnectionInfo

App version >=14.11

Obtain metainformation about the current device data network connectivity

getNetworkConnectionInfo: () => Promise<{
    connectionType: 'MOBILE' | 'WIFI ' | 'OTHER' | 'NONE';
    mobileConnectionType?:
        | '2G'
        | '3G'
        | '4G'
        | '5G'
        | 'OTHER'
        | 'PERMISSION_REQUIRED'
        | null;
    mobileCarrier?: string | null;
    mobileSignalStrength?:
        | 'NONE'
        | 'POOR'
        | 'MODERATE'
        | 'GOOD'
        | 'GREAT'
        | null;
}>;
  • connectionType: describes the network technology used currently for data
  • mobileConnectionType: in case connectionType is 'MOBILE' gives further details about the network technology used. PERMISSION_REQUIRED value will be returned only in Android when READ_PHONE_STATE permission has not been granted by the user. The permission request is already managed by the Android implementation itself.
  • mobileCarrier: identifies the carrier used for 'MOBILE' connectionType
  • mobileSignalStrength: gives a measure of the current signal strength for 'MOBILE' connectionType.

getPincodeInfo

App version >=24.2

Check if the pincode is enabled or not

getPincodeInfo: () => Promise<{
    status: 'enabled' | 'disabled'
}>;

getProfileImage

App version >=14.9

Read current profile picture

getProfileImage: () => Promise<{
    image: string | null
}>;
  • image: base64 encoded image or null if there is no image

startProfileImageFlow

App version >=14.9

Starts the native flow to change the profile picture

startProfileImageFlow: () => Promise<{
    image: string | null;
    isCancelled: boolean;
}>;
  • image: base64 encoded image or null if the image was removed or the flow cancelled
  • isCancelled: true if the user cancelled the flow

getDeviceTac

App version >=24.3

Get device TAC identifier.

getDeviceTac: () => Promise<{
    tac: string | null
}>;
  • tac: The TAC identifier is the first 8 digits of the IMEI. We already have a method to get the IMEI but to obtain this value, we need carrier privileges permission which in many cases we don't have. To get the TAC we don't need any special permission because it only identifies the device model, not the device itself. Will be null if it's not available (iOS devices or Android < 10).

triggerPinOrBiometricAuthentication

App version >=24.4

Triggers pin/biometric authentication if necessary, taking into account 3 possible scenarios:

  • If user has pin/biometric already configured in the app:
    • If last previous authentication (or last pin/biometric setup) is still valid, nothing will be presented to user and bridge method will succeed.
    • Otherwise, authentication will be required, blocking the user until it is performed.
  • In any other case, user will be taken directly to the screen where user can introduce a new PIN and enable any other authentication methods. In case user leaves the screen without providing an authentication method, bridge method will fail with 401 code.
triggerPinOrBiometricAuthentication: ({
    maxSecondsSinceLastValidation: number
}) => Promise<{
    result: 'USER_AUTHENTICATED' | 'USER_ENABLED_AUTHENTICATION' | 'LAST_AUTHENTICATION_STILL_VALID',
}>;
  • maxSecondsSinceLastValidation: if time elapsed since last authentication is less than the number of seconds specified here authentication will succeed without requesting it again.

focusNavbar

App version >= 24.9

Sets the screen reader focus on the native navigation bar. If the webview doesn't have a native navbar, the native app will respond with {focused: false}.

This is useful for accessibility purposes. We need the focus to be set in the navbar when we navigate to a new screen using client side navigation (React Router).

focusNavbar: () => Promise<{
    focused: boolean,
}>;

openOnboarding

Available in B2P App version >=24.10

Opens the app Onboarding (as if it where the first time the user logs in)

openOnboarding = () => Promise<void>

getBatteryInfo

App version >=24.10

Obtains information about the device battery status

getBatteryInfo: () => Promise<{
    batteryLevel: number | null;
    isPowerSafeMode: boolean;
}>;
  • batteryLevel: battery level in percentage (0 - 100). null if the battery information is unavailable.
  • isPowerSafeMode: true if the device is in power saving mode.

readTextFromClipboard

App version >=24.10

Reads the current text in the clipboard

readTextFromClipboard: () => Promise<string>;

writeTextToClipboard

App version >=24.10

Writes the given text to the clipboard

writeTextToClipboard: (text: string) => Promise<void>;

showLoadingOverlay / hideLoadingOverlay

App version >=24.10

Shows a loading overlay screen while a task is being performed. You can control when to hide it with the hideLoadingOverlay method.

showLoadingOverlay: ({
    /**
     * Whether the in animation is enabled (false by default)
     */
    inAnimation?: boolean;
    /**
     * Whether the out animation is enabled (false by default)
     */
    outAnimation?: boolean;
    /**
     * Minimum duration of the loop animation in milliseconds (0 by default)
     */
    minimumLoopDurationMs?: number;
    /**
     * whether the loop animation should be stopped immediately or not (true by default)
     */
    stopAnimationCycle?: boolean;
    /**
     * List of description texts to be shown one after the other
     */
    descriptions?: Array<string>;
    /**
     * Duration of each description in milliseconds (3000 by default)
     */
    descriptionDurationMs?: number;
    /**
     * After this timeout loading screen would be hidden automatically (20000 by default)
     */
    timeoutMs?: number;
    /**
     * (Only Android) If true, after loading screen has been hidden, if user presses android back button, webview window will close (true by default)
     */
    closeOnBackButtonPressAfterFinish?: boolean;
}) => Promise<void>;

hideLoadingOverlay: () => Promise<void>;

Example

await showLoadingOverlay({
    inAnimation: true,
    outAnimation: true,
    stopAnimationCycle: false,
    descriptions: ['Loading...', 'Please wait...'],
    descriptionDurationMs: 3000,
});
await doExpensiveTask();
await hideLoadingOverlay();

getInstallationId

App version >=24.11

Returns the application installation id. A 32 hexadecimal characters long string that represents one installation of the native app.

getInstallationId: () => Promise<{installationId: string}>;

getUnseenNotificationsBadge / setUnseenNotificationsBadge

App version >=24.12

get/set the number of unseen notifications in the inbox and the last time the counter was updated (timestamp in milliseconds).

getUnseenNotificationsBadge: () => Promise<{unseenNotificationCounter: number; lastUpdated: number}>;
setUnseenNotificationsBadge: ({unseenNotificationCounter: number; lastUpdated: number}) => Promise<void>;

When the webview is opened, it will ask to the native app for the unseen notifications badge (getUnseenNotificationsBadge). This allows the webview to know if the native app has received any push while the webview was closed. The webview will check the lastUpdated timestamp receibed from the native app with the one persisted in the webview localStorage, if it's different, the webview will fetch the inbox from server. When the webview updates their state, it will persist the lastUpdated timestamp in the localStorage and send it to the native app using the setUnseenNotificationsBadge. This way, the next time the webview use the getter, it will know if the lastUpdated matches with the one persisted in localStorage.

Error handling

If an uncontrolled error occurs, promise will be rejected with an error object:

{code: number, description: string}

Debugging

To inspect the bridge traffic, you can use the setLogger method:

setLogger((...args) => console.log(...args));

License

This project is licensed under the terms of the MIT license. See the LICENSE file.