1.0.12 • Published 10 months ago

webview-native-bridge v1.0.12

Weekly downloads
-
License
ISC
Repository
-
Last release
10 months ago

Using

Install

npm install webview-native-bridge

or

yarn add webview-native-bridge

Import

import bridge, { useBridgeWindow } from "webview-native-bridge";

Built-in functions

bridge.getPlatformAsync(): Promise<string>
bridge.getPlatformVersionAsync(): Promise<string>

bridge.checkPermissionAsync(permission: string): Promise<PermissionStatus>
bridge.requestPermissionAsync(permission: string, rationale?: Rationale): Promise<PermissionStatus>
// ex: permission = Permissions.android.ACCESS_FINE_LOCATION
// ex: permission = Permissions.android.LOCATION_WHEN_IN_USE
// ex: permission = Permissions.ios.CONTACTS

// FOR IOS ONLY
bridge.checkNotificationsPermissionAsync(): Promise<NotificationsPermissionResponse>
// FOR IOS ONLY
bridge.requestNotificationsPermissionAsync(options: NotificationPermissionOption[]): Promise<NotificationsPermissionResponse>

bridge.getGeoLocationAsync(request?: GeolocationRequest): Promise<GeolocationResponse>

bridge.setContentAsync(name: string, content: string): Promise<void>
bridge.getContentAsync(name: string): Promise<string>

bridge.showSmallAdsAsync(): Promise<void>
bridge.showFullscreenAdsAsync(): Promise<void>
bridge.showVideoAdsAsync(): Promise<void>

bridge.openInBrowserAsync(url: string): Promise<void>
bridge.openDeepLinkAsync(deepLink: string, fallbackUrl?: string)
bridge.canOpenDeepLinkAsync(deepLink: string): Promise<boolean>
bridge.openSettingsAsync(): Promise<void>

bridge.getFirebaseTokenAsync(): Promise<string>
bridge.getFirebaseInitialMessageAsync(): Promise<FirebaseMessage | null>

bridge.getContactsAsync(option?: ContactOption): Promise<Contact[]>

// FOR ANDROID ONLY
bridge.detectCallAsync(phoneNumber: string, callType: CallType[], timeoutInMs: number): Promise<boolean>

bridge.getColorSchemeAsync(): Promise<ColorSchemeName>
bridge.getAppStateAsync(): Promise<AppStateStatus>
bridge.getBatteryLevelAsync(): Promise<number>

bridge.getStatusBarHeightAsync(): Promise<number>
bridge.setStatusBarStyleAsync(style: StatusBarStyle): Promise<void>
bridge.setStatusBarHiddenAsync(hidden: boolean): Promise<void>

bridge.addDisallowBackUrlsAsync(url: string[] | string): Promise<boolean>

bridge.vibrateAsync(pattern: number[], repeat?: boolean = false): Promise<void>
bridge.cancelVibrateAsync(): Promise<void>

bridge.getBrightnessAsync(): Promise<number>
bridge.setBrightnessAsync(value: number): Promise<void>

bridge.setTorchStateAsync(torchOn: boolean): Promise<void>

bridge.takePhotoAsync(option: TakePhotoOption): Promise<TakePhotoResult>
bridge.takeVideoAsync(option: TakeVideoOption): Promise<TakeVideoResult>
bridge.scanQrCodeAsync(option: ScanQrCodeOption): Promise<string>

bridge.downloadFileAsync(url: string): Promise<void>
bridge.uploadFileAsync(fileUploadRequest: FileUploadRequest): Promise<FileUploadResponse>

bridge.storeFileAsync(name: string, url: string): Promise<StoreFileResult>
bridge.hasFileAsync(name: string): Promise<boolean>
bridge.removeFileAsync(name: string): Promise<void>

bridge.displayPdfAsync(filename: string): Promise<void>

bridge.shareAsync(content: ShareContent): Promise<ShareAction>
bridge.copyToClipboard(text: string): Promise<void>,

bridge.getEnvironmentOptionsAsync(): Promise<EnvironmentOption[]>,
bridge.setEnvironmentAsync(envCode: string): Promise<void>,
bridge.addEnvironmentAsync(env: EnvironmentOption): Promise<EnvironmentAdditionResult>,
bridge.getCurrentEnvironmentAsync(): Promise<EnvironmentOption>,
bridge.getVersionInfoAsync(): Promise<VersionInfo>
bridge.getCodeVersionInfoAsync(): Promise<CodeVersionInfo>

bridge.restartAsync(): Promise<void>

Built-in events

bridge.addFirebaseMessageListener(listener: FirebaseMessageHandler)
bridge.removeFirebaseMessageListeners()
bridge.removeFirebaseMessageListener(listener: FirebaseMessageHandler)

bridge.addAppStateChangedListener(listener: AppStateChangedBridgeHandler)
bridge.removeAppStateChangedListeners()
bridge.removeAppStateChangedListener(listener: AppStateChangedBridgeHandler)

bridge.addBatteryLevelChangedListener(listener: BatteryLevelChangedBridgeHandler)
bridge.removeBatteryLevelChangedListeners()
bridge.removeBatteryLevelChangedListener(listener: BatteryLevelChangedBridgeHandler)

bridge.addConnectionChangedListener(listener: ConnectionChangedBridgeHandler)
bridge.removeConnectionChangedListeners()
bridge.removeConnectionChangedListener(listener: ConnectionChangedBridgeHandler)

Call customize function

bridge.$sendCommandAsync(name: string, parameters?: any[]);

Set mock

bridge.$setMock(sendCommandAsyncFunction: SendCommandFunction);

For hosting in React Native app

useBridgeWindow((window as any).ReactNativeWebView as Window);

For hosting in Native app

useBridgeWindow((window as any).NAME_OF_INJECTED_WEBVIEW_WINDOW as Window);

References

Permission names

const Permissions = {
    android: {
        ACCEPT_HANDOVER: 'android.permission.ACCEPT_HANDOVER',
        ACCESS_BACKGROUND_LOCATION: 'android.permission.ACCESS_BACKGROUND_LOCATION',
        ACCESS_COARSE_LOCATION: 'android.permission.ACCESS_COARSE_LOCATION',
        ACCESS_FINE_LOCATION: 'android.permission.ACCESS_FINE_LOCATION',
        ACTIVITY_RECOGNITION: 'android.permission.ACTIVITY_RECOGNITION',
        ADD_VOICEMAIL: 'com.android.voicemail.permission.ADD_VOICEMAIL',
        ANSWER_PHONE_CALLS: 'android.permission.ANSWER_PHONE_CALLS',
        BODY_SENSORS: 'android.permission.BODY_SENSORS',
        CALL_PHONE: 'android.permission.CALL_PHONE',
        CAMERA: 'android.permission.CAMERA',
        GET_ACCOUNTS: 'android.permission.GET_ACCOUNTS',
        PROCESS_OUTGOING_CALLS: 'android.permission.PROCESS_OUTGOING_CALLS',
        READ_CALENDAR: 'android.permission.READ_CALENDAR',
        READ_CALL_LOG: 'android.permission.READ_CALL_LOG',
        READ_CONTACTS: 'android.permission.READ_CONTACTS',
        READ_EXTERNAL_STORAGE: 'android.permission.READ_EXTERNAL_STORAGE',
        READ_PHONE_NUMBERS: 'android.permission.READ_PHONE_NUMBERS',
        READ_PHONE_STATE: 'android.permission.READ_PHONE_STATE',
        READ_SMS: 'android.permission.READ_SMS',
        RECEIVE_MMS: 'android.permission.RECEIVE_MMS',
        RECEIVE_SMS: 'android.permission.RECEIVE_SMS',
        RECEIVE_WAP_PUSH: 'android.permission.RECEIVE_WAP_PUSH',
        RECORD_AUDIO: 'android.permission.RECORD_AUDIO',
        SEND_SMS: 'android.permission.SEND_SMS',
        USE_SIP: 'android.permission.USE_SIP',
        WRITE_CALENDAR: 'android.permission.WRITE_CALENDAR',
        WRITE_CALL_LOG: 'android.permission.WRITE_CALL_LOG',
        WRITE_CONTACTS: 'android.permission.WRITE_CONTACTS',
        WRITE_EXTERNAL_STORAGE: 'android.permission.WRITE_EXTERNAL_STORAGE',
    },
    ios: {
        APP_TRACKING_TRANSPARENCY: 'ios.permission.APP_TRACKING_TRANSPARENCY',
        BLUETOOTH_PERIPHERAL: 'ios.permission.BLUETOOTH_PERIPHERAL',
        CALENDARS: 'ios.permission.CALENDARS',
        CAMERA: 'ios.permission.CAMERA',
        CONTACTS: 'ios.permission.CONTACTS',
        FACE_ID: 'ios.permission.FACE_ID',
        LOCATION_ALWAYS: 'ios.permission.LOCATION_ALWAYS',
        LOCATION_WHEN_IN_USE: 'ios.permission.LOCATION_WHEN_IN_USE',
        MEDIA_LIBRARY: 'ios.permission.MEDIA_LIBRARY',
        MICROPHONE: 'ios.permission.MICROPHONE',
        MOTION: 'ios.permission.MOTION',
        PHOTO_LIBRARY: 'ios.permission.PHOTO_LIBRARY',
        PHOTO_LIBRARY_ADD_ONLY: 'ios.permission.PHOTO_LIBRARY_ADD_ONLY',
        REMINDERS: 'ios.permission.REMINDERS',
        SIRI: 'ios.permission.SIRI',
        SPEECH_RECOGNITION: 'ios.permission.SPEECH_RECOGNITION',
        STOREKIT: 'ios.permission.STOREKIT',
    }
}

PermissionStatus

type PermissionStatus = "unavailable" | "blocked" | "denied" | "granted" | "limited"

Rationale

interface Rationale {
    title: string;
    message: string;
    buttonPositive: string;
    buttonNegative?: string;
    buttonNeutral?: string;
}

PermissionStatusResults

const PermissionStatusResults = {
    UNAVAILABLE: "unavailable",
    BLOCKED: "blocked",
    DENIED: "denied",
    GRANTED: "granted",
    LIMITED: "limited",
}

NotificationsPermissionResponse

interface NotificationsPermissionResponse {
    status: PermissionStatus;
    settings: NotificationPermissionSettings;
}

interface NotificationPermissionSettings {
    alert?: boolean;
    badge?: boolean;
    sound?: boolean;
    carPlay?: boolean;
    criticalAlert?: boolean;
    provisional?: boolean;
    lockScreen?: boolean;
    notificationCenter?: boolean;
}

NotificationPermissionOption

type NotificationPermissionOption = 'alert' | 'badge' | 'sound' | 'carPlay' | 'criticalAlert' | 'provisional'

GeolocationRequest

interface GeolocationRequest {
    enableHighAccuracy?: boolean,
    timeout?: number;
    maximumAge?: number;
}

GeolocationResponse

interface GeolocationResponse {
    coords: {
        latitude: number;
        longitude: number;
        altitude: number | null;
        accuracy: number;
        altitudeAccuracy: number | null;
        heading: number | null;
        speed: number | null;
    };
    timestamp: number;
}

ContactOption

interface ContactOption {
    includePhoto?: boolean,
    matchingString?: string
}

Contact

interface Contact {
    recordID: string;
    backTitle: string;
    company: string|null;
    emailAddresses: ContactEmailAddress[];
    displayName: string;
    familyName?: string;
    givenName: string;
    middleName: string;
    jobTitle: string;
    phoneNumbers: ContactPhoneNumber[];
    hasThumbnail: boolean;
    thumbnailPath: string;
    postalAddresses: ContactPostalAddress[];
    prefix: string;
    suffix: string;
    department: string;
    birthday: ContactBirthday;
    imAddresses: ContactInstantMessageAddress[]
    note: string;
}

interface ContactEmailAddress {
    label: string;
    email: string;
}

interface ContactPhoneNumber {
    label: string;
    number: string;
}

interface ContactPostalAddress {
    label: string;
    formattedAddress: string;
    street: string;
    pobox: string;
    neighborhood: string;
    city: string;
    region: string;
    state: string;
    postCode: string;
    country: string;
}

interface ContactInstantMessageAddress {
    username: string;
    service: string;
}

interface ContactBirthday {
    day: number;
    month: number;
    year: number;
}

Call

type CallType = "OUTGOING" | "INCOMING" | "MISSED" | "UNKNOWN";

ColorSchemeName

type ColorSchemeName = 'light' | 'dark' | null | undefined

AppStateStatus

type AppStateStatus = 'active' | 'background' | 'inactive' | 'unknown' | 'extension'

StatusBarStyle

type StatusBarStyle = 'default' | 'light-content' | 'dark-content'

TakePhotoOption

interface TakePhotoOption {
    camera?: "back" | "front",
    maxWidth?: number,
    maxHeight?: number,
    quality?: number,
}

TakePhotoResult

interface TakePhotoResult {
    uri?: string;
    width?: number;
    height?: number;
    fileSize?: number;
    type?: string;
    fileName?: string;
}

TakeVideoOption

interface TakeVideoOption {
    camera?: "back" | "front",
    maxWidth?: number,
    maxHeight?: number,
    quality?: "low" | "medium" | "high",
    durationLimit?: number, 
}

TakeVideoResult

interface TakeVideoResult {
    uri?: string;
    width?: number;
    height?: number;
    fileSize?: number;
    type?: string;
    fileName?: string;
    duration?: number;
}

ScanQrCodeOption

interface ScanQrCodeOption {
    camera?: "back" | "front", 
    type?: "qrCode" | "barCode" | "both"
}

FileUploadRequest

interface FileUploadRequest {
    method?: 'POST' | 'PUT' | 'PATCH' | string,
    url: string,
    file: string,
    name?: string,
    headers?: Record<string, string>
}

FileUploadResponse

interface FileUploadResponse {
    statusCode: number,
    headers: Record<string, string>,
    body: string
}

StoreFileResult

interface StoreFileResult {
    size: number,
    statusCode: number
}

ShareContent

type ShareContent = {
        title?: string;
        message: string;
    } | {
        title?: string;
        url: string;
    }

ShareAction

type ShareAction = 'sharedAction' | 'dismissedAction'

EnvironmentOption

interface EnvironmentOption {
    name: string,
    code: string,
    url: {
        phone: string,
        tablet?: string
    }
}

EnvironmentAdditionResult

interface EnvironmentAdditionResult {
    success: boolean,
    message: string,
}

VersionInfo

interface VersionInfo {
    versionName: string,
    versionCode: number
}

CodeVersionInfo

interface CodeVersionInfo {
    current: string,
    next: number
}

FirebaseMessage

interface FirebaseMessage {
    /**
    * The collapse key a message was sent with. Used to override existing messages with the same
    * key.
    */
    collapseKey?: string;

    /**
    * A unique ID assigned to every message.
    */
    messageId?: string;

    /**
    * The message type of the message.
    */
    messageType?: string;
    /**
    * The topic name or message identifier.
    */
    from?: string;
    /**
    * The address for the message.
    */
    to?: string;

    /**
    * The time to live for the message in seconds.
    *
    * Defaults to 3600.
    */
    ttl?: number;

    /**
    * The time the message was sent, in milliseconds since the start of unix epoch
    */
    sentTime?: number;

    /**
    * Any additional data sent with the message.
    */
    data?: { [key: string]: string };

    /**
    * Additional Notification data sent with the message
    */
    notification?: FirebaseNotification;

    /**
    * Whether the iOS APNs message was configured as a background update notification.
    *
    * @platform ios iOS
    */
    contentAvailable?: boolean;

    /**
    * Whether the iOS APNs `mutable-content` property on the message was set
    * allowing the app to modify the notification via app extensions.
    *
    * @platform ios iOS
    */
    mutableContent?: boolean;

    /**
    * The iOS category this notification is assigned to.
    *
    * @platform ios iOS
    */
    category?: string;

    /**
    * An iOS app specific identifier used for notification grouping.
    */
    threadId?: string;
}

interface FirebaseNotification {
    /**
    * The notification title.
    */
    title?: string,

    /**
    * The native localization key for the notification title.
    */
    titleLocKey?: string,

    /**
    * Any arguments that should be formatted into the resource specified by titleLocKey.
    */
    titleLocArgs?: string[],

    /**
    * The notification body content.
    */
    body?: string,

    /**
    * The native localization key for the notification body content.
    */
    bodyLocKey?: string,

    /**
    * Any arguments that should be formatted into the resource specified by bodyLocKey.
    */
    bodyLocArgs?: string[],

    ios?: {
        /**
        * The notification's subtitle.
        */
        subtitle?: string,

        /**
        * The native localization key for the notification's subtitle.
        */
        subtitleLocKey?: string,

        /**
        * Any arguments that should be formatted into the resource specified by subtitleLocKey.
        */
        subtitleLocArgs?: string[],

        /**
        * The value of the badge on the home screen app icon.
        * If not specified, the badge is not changed.
        * If set to 0, the badge has been removed.
        */
        badge?: string,
    },

    /**
    * Additional Android specific properties set on the notification.
    */
    android?: {
        /**
        * The sound played when the notification was delivered on the device (channel settings permitted).
        *
        * Set as "default" if the default device notification sound was used.
        */
        sound?: string,

        /**
        * The channel ID set on the notification. If not set, the notification uses the default
        * "Miscellaneous" channel set by FCM.
        */
        channelId?: string,

        /**
        * The custom color used to tint the notification content.
        */
        color?: string,

        /**
        * The custom small icon used to display on the notification. If not set, uses the default
        * application icon defined in the AndroidManifest file.
        */
        smallIcon?: string,

        /**
        * The custom image was provided and displayed in the notification body.
        */
        imageUrl?: string,

        /**
        * Deep link URL provided to the notification.
        */
        link?: string,

        /**
        * The current unread notification count for this application, managed by the device.
        */
        count?: number,

        /**
        * Name of the click action set on the notification.
        */
        clickAction?: string,

        /**
        * The notification priority.
        *
        * Note, on devices which have channel support (Android 8.0 (API level 26) +),
        * this value will be ignored. Instead, the channel "importance" level is used.
        */
        priority?:
        | FirebaseNotificationAndroidPriority.PRIORITY_MIN
        | FirebaseNotificationAndroidPriority.PRIORITY_LOW
        | FirebaseNotificationAndroidPriority.PRIORITY_DEFAULT
        | FirebaseNotificationAndroidPriority.PRIORITY_HIGH
        | FirebaseNotificationAndroidPriority.PRIORITY_MAX,

        /**
        * Ticker text set on the notification.
        *
        * Ticker text is used for devices with accessibility enabled (e.g. to read out the message).
        */
        ticker?: string,

        /**
        * The visibility of a notification. This value determines how the notification is shown on the users
        * devices (e.g. on the lock-screen).
        */
        visibility?:
        | FirebaseNotificationAndroidVisibility.VISIBILITY_SECRET
        | FirebaseNotificationAndroidVisibility.VISIBILITY_PRIVATE
        | FirebaseNotificationAndroidVisibility.VISIBILITY_PUBLIC,
    },
}  

enum FirebaseNotificationAndroidVisibility {
    /**
    * Do not reveal any part of this notification on a secure lock-screen.
    */
    VISIBILITY_SECRET = -1,

    /**
    * Show this notification on all lock-screens, but conceal sensitive or private information on secure lock-screens.
    */
    VISIBILITY_PRIVATE = 0,

    /**
    * Show this notification in its entirety on all lock-screens.
    */
    VISIBILITY_PUBLIC = 1,
}

enum FirebaseNotificationAndroidPriority {
    /**
    * The application small icon will not show up in the status bar, or alert the user. The notification
    * will be in a collapsed state in the notification shade and placed at the bottom of the list.
    */
    PRIORITY_MIN = -2,

    /**
    * The application small icon will show in the device status bar, however the notification will
    * not alert the user (no sound or vibration). The notification will show in it's expanded state
    * when the notification shade is pulled down.
    */
    PRIORITY_LOW = -1,

    /**
    * When a notification is received, the device smallIcon will appear in the notification shade.
    * When the user pulls down the notification shade, the content of the notification will be shown
    * in it's expanded state.
    */
    PRIORITY_DEFAULT = 0,

    /**
    * Notifications will appear on-top of applications, allowing direct interaction without pulling
    * own the notification shade. This level is used for urgent notifications, such as
    * incoming phone calls, messages etc, which require immediate attention.
    */
    PRIORITY_HIGH = 1,

    /**
    * The priority highest level a notification can be set at.
    */
    PRIORITY_MAX = 2,
}

Events

BridgeHandlerArgument

interface BridgeHandlerArgument<T> {
    name: string,
    data: T
}

BridgeHandler

type BridgeHandler = (arg: BridgeHandlerArgument<any>) => Promise<boolean> | Promise<undefined> | Promise<void> | boolean | undefined | void;

FirebaseMessageHandler

type FirebaseMessageHandler = (arg: BridgeHandlerArgument<FirebaseMessage>) => Promise<boolean> | Promise<undefined> | Promise<void> | boolean | undefined | void

AppStateChangedBridgeHandler

type AppStateChangedBridgeHandler = (arg: BridgeHandlerArgument<string>) => Promise<boolean> | Promise<undefined> | Promise<void> | boolean | undefined | void

BatteryLevelChangedBridgeHandler

type BatteryLevelChangedBridgeHandler = (arg: BridgeHandlerArgument<number>) => Promise<boolean> | Promise<undefined> | Promise<void> | boolean | undefined | void;

ConnectionChangedBridgeHandler

type ConnectionChangedBridgeHandler = (arg: BridgeHandlerArgument<string>) => Promise<boolean> | Promise<undefined> | Promise<void> | boolean | undefined | void
1.0.12

10 months ago

1.0.11

12 months ago

1.0.10

2 years ago

1.0.9

2 years ago

1.0.8

2 years ago

1.0.7

2 years ago

1.0.6

2 years ago

1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago