@tef-novum/webview-bridge
TypeScript icon, indicating that this package has built-in type declarations

3.33.0 • Public • Published

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

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'});

updateNavigationBar

App version >= 10.7: Partial support
App version >= 11.8: expandedTitle
App version >= 14.8: Additional properties and deprecations

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

type NavigationBarIcon = {
    /** 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
  • 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',
    leftNavigationIcons: [
        {
            name: 'icon name',
            iconEnum: 'SOME_ICON',
            badge: {
                show: true,
                nativeLogic: 'INBOX',
            },
        },
    ],
    rightNavigationIcons: [
        {
            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

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;
}) => Promise<boolean>;

Example

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

nativeAlert

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.

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;
        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

setCustomerHash

Sets the hash of the current subscription for the customer, which is used for tracking purposes.

setCustomerHash(
    'e658ad63bef9b86863b487697dfb75d64bddb6191ec14099abe443655f6b7cc6',
);

getCustomerHash

Gets the hash of the current subscription for the customer, which is used for tracking purposes.

getCustomerHash().then(({hash}) => { ... });

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

A method that requests a user logout.

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

getTopazToken

Returns the Topaz token.

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

showAppRating

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).

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));

openOnboarding

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

openOnboarding = () => Promise<void>

License

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

Readme

Keywords

none

Package Sidebar

Install

npm i @tef-novum/webview-bridge

Weekly Downloads

1,229

Version

3.33.0

License

MIT

Unpacked Size

311 kB

Total Files

25

Last publish

Collaborators

  • pladaria
  • atabel
  • jokepk
  • smorchon
  • julio.munoz.gaya
  • cesar.lopezdefelipe.telefonica
  • juandavid.vegarodriguez