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');
} else {
myCustomAlert('Hello');
}
You may want to detect if the page is displayed inside a regular browser or an
Android or iOS WebView.
const isWebView = () => isWebViewBridgeAvailable();
const isAndroidWebView = () =>
isWebViewBridgeAvailable() && navigator.userAgent.includes('Android');
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
share({text: 'Hello, world!'});
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',
});
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 = {
name: string;
iconEnum?: string;
icon?: {
url: string;
urlDark?: string;
};
badge?: {
show: boolean;
nativeLogic?: 'INBOX' | 'PROFILE';
number?: number;
};
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 titleexpandedTitle
: 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.8showBackButton
: shows or hides back icon in NavigationBarshowReloadButton
: shows or hides NavigationBar Reload buttonshowProfileButton
: DEPRECATED. New apps will ignore this fieldbackgroundColor
: change NavigationBar background color, use a hex color
string (for example: '#FF128A'
)leftActions
: array of icons to show in the left siderightActions
: array of icons to show in the right sidecolorVariant
: 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 usedresetToDefaultState
: 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
updateNavigationBar({title: 'Hello, World!'});
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`);
});
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
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');
});
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') {
}
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" applicationisInstalled
: boolean to see if the app is installedappUrl
: string url to launch an app installed on the phonemarketUrl
: 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 devicetotalBytes
: 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 esimeid
: "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 propertyname
: name of the propertyvalue
: 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}>
getTopazValues
App version >=24.9
Returns an object containing values from the
Topaz SDK.
getTopazValues = () => Promise<{syncId?: 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>
:warning: 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 count
value - 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 datamobileConnectionType
: 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' connectionTypemobileSignalStrength
: 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
cancelledisCancelled
: 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,
}>;
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.