Braze

Index

Type aliases

InitializationOptions

InitializationOptions: { allowCrawlerActivity?: undefined | false | true; allowUserSuppliedJavascript?: undefined | false | true; appVersion?: undefined | string; appVersionNumber?: undefined | string; baseUrl: string; contentSecurityNonce?: undefined | string; deviceId?: undefined | string; devicePropertyAllowlist?: string[]; disablePushTokenMaintenance?: undefined | false | true; doNotLoadFontAwesome?: undefined | false | true; enableLogging?: undefined | false | true; enableSdkAuthentication?: undefined | false | true; inAppMessageZIndex?: undefined | number; localization?: undefined | string; manageServiceWorkerExternally?: undefined | false | true; minimumIntervalBetweenTriggerActionsInSeconds?: undefined | number; noCookies?: undefined | false | true; openCardsInNewTab?: undefined | false | true; openInAppMessagesInNewTab?: undefined | false | true; requireExplicitInAppMessageDismissal?: undefined | false | true; safariWebsitePushId?: undefined | string; serviceWorkerLocation?: undefined | string; sessionTimeoutInSeconds?: undefined | number }

Supported initialization options

Type declaration

  • Optional allowCrawlerActivity?: undefined | false | true

    By default, the Braze Web SDK ignores activity from known spiders or web crawlers, such as Google, based on the user agent string. This saves data points, makes analytics more accurate, and may improve page rank. However, if you want Braze to log activity from these crawlers instead, you may set this option to true.

  • Optional allowUserSuppliedJavascript?: undefined | false | true

    By default, the Braze Web SDK does not allow user-supplied Javascript click actions or enable HTML in-app messages, as they allow Braze dashboard users to run Javascript on your site. To indicate that you trust the Braze dashboard users to write non-malicious Javascript click actions, set this property to true.

  • Optional appVersion?: undefined | string

    If you provide a value for this option, user events sent to Braze will be associated with the given version, which can be used for user segmentation.

  • Optional appVersionNumber?: undefined | string

    A numerical app version value which can be used for user segmentation. This value must be sent with four fields, such as "1.2.3.4", otherwise it will be ignored.

    Note: appVersion must also be set, either with the same value or a unique name for this version.

  • baseUrl: string

    This option is required to configure the Braze Web SDK to use the appropriate endpoint for your integration - for example:

       braze.initialize('YOUR-API-KEY-HERE', { baseUrl: 'sdk.iad-03.braze.com' })
  • Optional contentSecurityNonce?: undefined | string

    If you provide a value for this option, the Braze SDK will add the nonce to any <script> and <style> elements created by the SDK. This can be used to permit the Braze SDK to work with your website's Content Security Policy. Note that in addition to setting this nonce, you may also need to allow FontAwesome to load, which you can do by either adding use.fontawesome.com to your Content Security Policy allowlist or by using the doNotLoadFontAwesome option and loading it manually.

  • Optional deviceId?: undefined | string

    By default, Braze will assign a random guid as the device ID. Provide a value for this configuration option to override that default with a value of your own.

  • Optional devicePropertyAllowlist?: string[]

    By default, the Braze SDK automatically detects and collects all device properties in DeviceProperties. To override this behavior, provide an array of DeviceProperties. To disable all properties being sent to Braze servers, provide an empty array. Note that without some properties, not all features will function properly. For instance, without the time zone, local timezone delivery will not function.

  • Optional disablePushTokenMaintenance?: undefined | false | true

    By default, users who have already granted web push permission (e.g. through requestPushPermission or from a prior push provider) will sync their push token with the Braze backend automatically on new session to ensure deliverability. To disable this behavior, set this option to true.

  • Optional doNotLoadFontAwesome?: undefined | false | true

    Braze uses Font Awesome for in-app message icons. By default, Braze will automatically load FontAwesome 4.7.0 from the FontAwesome CDN. To disable this behavior (e.g. because your site uses a customized version of FontAwesome), set this option to true. Note that if you do this, you are responsible for ensuring that FontAwesome is loaded on your site - otherwise in-app messages may not render correctly.

  • Optional enableLogging?: undefined | false | true

    Set to true to enable logging by default. Note that this will cause Braze to log to the javascript console, which is visible to all users! You should probably remove this or provide an alternate logger with setLogger before you release your page to production.

  • Optional enableSdkAuthentication?: undefined | false | true

    Set to true to enable the SDK Authentication feature. For more information about SDK Authentication, see our Product Documentation.

  • Optional inAppMessageZIndex?: undefined | number

    By default, the Braze SDK will show In-App Messages with a z-index of 9001 for the screen overlay, 9011 for the actual in-app message, and 9021 for the message's close button. Provide a value for this option to override these default z-indexes. The value provided will be used for the backdrop, value + 1 will be used for the in-app message, and value + 2 will be used for the close button.

  • Optional localization?: undefined | string

    By default, any SDK-generated user-visible messages will be displayed in the user's browser language. Provide a value for this option to override that behavior and force a specific language. The value for this option should be a ISO 639-1 Language Code. If a desired localization is not available, the SDK will default to English. See also User.setLanguage for setting the language you use within the Braze dashboard to localize your own messaging content.

  • Optional manageServiceWorkerExternally?: undefined | false | true

    By default, requestPushPermission/unregisterPush assume that they control and can register and unregister the site's service worker. If you have your own service worker that you register and control the lifecycle of, set this option to true and the Braze SDK will not register or unregister a service worker. If you set this option to true, in order for push to function correctly you must register the service worker yourself BEFORE calling requestPushPermission, and ensure that it contains Braze's service worker code, either with self.importScripts('https://js.appboycdn.com/web-sdk-develop/5.2/service-worker.js'); or by including the content of that file directly. When this option is true, the serviceWorkerLocation option is irrelevant and is ignored.

  • Optional minimumIntervalBetweenTriggerActionsInSeconds?: undefined | number

    By default, a trigger action will only fire if at least 30 seconds have elapsed since the last trigger action. Provide a value for this configuration option to override that default with a value of your own. We do not recommend making this value any smaller than 10 to avoid spamming the user with notifications.

  • Optional noCookies?: undefined | false | true

    By default, the Braze SDK will store small amounts of data (user ids, session ids), in cookies. This is done to allow Braze to recognize users and sessions across different subdomains of your site. If this presents a problem for you, pass true for this option to disable cookie storage and rely entirely on HTML 5 localStorage to identify users and sessions. The downside of this configuration is that you will be unable to recognize users across subdomains of your site.

  • Optional openCardsInNewTab?: undefined | false | true

    By default, links from Card objects load in the current tab or window. Set this option to true to make links from cards open in a new tab or window.

  • Optional openInAppMessagesInNewTab?: undefined | false | true

    By default, links from in-app message clicks load in the current tab or a new tab as specified in the dashboard on a message-by-message basis. Set this option to true to force all links from in-app message clicks open in a new tab or window.

  • Optional requireExplicitInAppMessageDismissal?: undefined | false | true

    By default, when an in-app message is showing, pressing the escape button or a click on the greyed-out background of the page will dismiss the message. Set this option to true to prevent this behavior and require an explicit button click to dismiss messages.

  • Optional safariWebsitePushId?: undefined | string

    If you support Safari push, you must specify this option with the website push ID that you provided to Apple when creating your Safari push certificate (starts with "web", e.g. "web.com.example.domain").

  • Optional serviceWorkerLocation?: undefined | string

    By default, when registering users for web push notifications Braze will look for the required service worker file in the root directory of your web server at /service-worker.js. If you want to host your service worker at a different path on that server, provide a value for this option that is the absolute path to the file, e.g. /mycustompath/my-worker.js. VERY IMPORTANT: setting a value here limits the scope of push notifications on your site. For instance, in the above example, because the service worker file is located within the /mycustompath/ directory, requestPushPermission MAY ONLY BE CALLED from web pages that start with http://yoursite.com/mycustompath/.

  • Optional sessionTimeoutInSeconds?: undefined | number

    By default, sessions time out after 30 minutes of inactivity. Provide a value for this configuration option to override that default with a value of your own.

Functions

addSdkMetadata

  • addSdkMetadata(sdkMetadata: string[]): boolean
  • Adds SDK Metadata. This method is automatically called based on the integration method.

    Parameters

    Returns boolean

    Whether or not the array of metadata is valid.

automaticallyShowInAppMessages

  • automaticallyShowInAppMessages(): string
  • Automatically display in-app messages when they are triggered. This method should be called before calling openSession.

    Returns string

    The identifier of the subscription created. This can be passed to removeSubscription to cancel the subscription.

changeUser

  • changeUser(userId: string, signature?: undefined | string): void
  • When a user first uses Braze on a device they are considered "anonymous". Use this method to identify a user with a unique ID, which enables the following:

    • If the same user is identified on another device, their user profile, usage history and event history will be shared across devices.
    • If your app is used on the same browser by multiple people, you can assign each of them a unique identifier to track them separately. Only the most recent user on a particular browser will receive push notifications and in-app messages.

    When you request a user switch (which is any call to changeUser where the new user ID is not the same as the existing user ID), the current session for the previous user (anonymous or not) is automatically ended and a new session is started. Similarly, following a call to changeUser, any events which fire are guaranteed to be for the new user -- if an in-flight server request completes for the old user after the user switch no events will fire, so you do not need to worry about filtering out events from Braze for old users.

    Additionally, if you identify a user which has never been identified on another device, the entire history of that user as an "anonymous" user on this device will be preserved and associated with the newly identified user. However, if you identify a user which has been identified in another app, any history which was already flushed to the server for the anonymous user on this device will be merged into the identified user. Any fields that already exist on the identified user will not be overwritten, and the merge is limited to the fields listed here.

    Note: Once you identify a user, you cannot revert to the "anonymous" user. The transition from anonymous to identified tracking is only allowed once because the initial anonymous user receives special treatment to allow for preservation of their history. As a result, we recommend against changing the user ID just because your app has entered a "logged out" state because it makes you unable to target the previously logged out user with re-engagement campaigns. If you anticipate multiple users on the same device, but only want to target one of them when your app is in a logged out state, we recommend separately keeping track of the user ID you want to target while logged out and switching back to that user ID as part of your app's logout process.

    Parameters

    • userId: string

      A unique identifier for this user. Limit 997 bytes. These User IDs should be private and not easily guessable (e.g. not a plain email address or username).

    • Optional signature: undefined | string

      An encrypted signature to be used to authenticate the current user. You can update the signature using the setSdkAuthenticationSignature method. This signature will only have an effect if the enableSdkAuthentication initialization option is set to true.

    Returns void

deferInAppMessage

  • deferInAppMessage(inAppMessage: InAppMessage): boolean | undefined
  • Defers the display of given in-app message for a future pageload. The deferred in-app message can be retrieved by calling getDeferredInAppMessage, and displayed using showInAppMessage. Deferring an in-app message will overwrite any previously deferred in-app message.

    Note: Be sure to subscribe to clicked / dismissed events on this in-app message only after retrieving it using getDeferredInAppMessage. Any subscriptions made before calling deferInAppMessage will not be persisted. Also note that the in-app message deferred here will be cleared out when in-app message triggers have been refreshed from the Braze backend.

    Parameters

    • inAppMessage: InAppMessage

      The message to defer for later display.

    Returns boolean | undefined

    Whether or not the message was successfully deferred. Returns undefined if the SDK has not been initialized.

destroy

  • destroy(): void
  • Destroys this braze instance, destroying all subscription callbacks and releasing member variables which retain memory.

    Returns void

destroyFeed

  • destroyFeed(): void
  • Destroy any Braze news feed currently showing. This method will appropriately clean up any retained resources and also display the hiding animation, and so should be used instead of manually removing feed html from the DOM.

    Returns void

disableSDK

  • disableSDK(): void
  • Sets a cookie that causes all subsequent calls to the Braze Web SDK to be ignored and all subsequent analytics to cease being sent to the Braze backend. If you have multiple subdomains, this method MUST be called from the same subdomain that push was registered from to work properly. This is useful for customer opt-outs. If the customer clears website data, tracking will resume.

    Returns void

enableSDK

  • enableSDK(): void
  • Removes the cookie set by disableSDK, causing subsequent calls to the Braze Web SDK to function. You must call initialize after calling this method before calling subsequent methods.

    Returns void

getAllFeatureFlags

getCachedContentCards

  • Get all currently available cards from the last content cards refresh.

    Returns ContentCards

    • A ContentCards object which includes all currently available Card objects from the last content cards refresh.

getCachedFeed

  • getCachedFeed(): Feed
  • Get all unexpired cards from the last news feed refresh.

    Returns Feed

    • A Feed object which includes all unexpired Card objects from the last news feed refresh.

getDeferredInAppMessage

  • getDeferredInAppMessage(): InAppMessage | null | undefined
  • Retrieves the in-app message that was most recently deferred for display with deferInAppMessage.

    Note: Retrieving the deferred in-app message here will clear it from storage.

    Returns InAppMessage | null | undefined

    The deferred in-app message if it exists, or returns null. Returns undefined if the SDK has not been initialized.

getDeviceId

  • getDeviceId(): string | undefined
  • getDeviceId(callback: (deviceId: string) => void): void
  • Retrieves the 'device id,' a randomly generated ID that is stored on the browser. This ID resets for private browsing sessions and when website data is cleared. For example:

    console.log('The device id is ' + braze.getDeviceId());

    Returns string | undefined

  • Asynchronously retrieves the 'device id,' a randomly generated ID that is stored on the browser. This ID resets for private browsing sessions and when website data is cleared. For example:

    braze.getDeviceId(function(deviceId) {
       console.log('The device id is ' + deviceId);
    });
    deprecated
    • The getDeviceId callback is deprecated. Access the method's return value directly instead.

    Parameters

    • callback: (deviceId: string) => void

      Asynchronous callback - this will be invoked with the deviceId.

        • (deviceId: string): void
        • Parameters

          • deviceId: string

          Returns void

    Returns void

getFeatureFlag

  • getFeatureFlag(id: string): FeatureFlag | null | undefined
  • Gets a feature flag by its ID.

    Parameters

    • id: string

      The ID of the feature flag.

    Returns FeatureFlag | null | undefined

    • An object of type FeatureFlag, if feature flag with given ID exists. The method returns null if feature flag does not exist, or if feature flags are disabled. Returns undefined if the SDK has not been initialized.

getUser

  • getUser(): User | undefined
  • Returns User | undefined

    The user currently being tracked by Braze, used for querying the tracked user id and setting user attributes. Should only be accessed via the getUser function. Returns undefined if the SDK has not been initialized.

handleBrazeAction

  • handleBrazeAction(url: string, openLinkInNewTab?: undefined | false | true): void
  • Handle links from within a message. This method will redirect valid links, or will parse and handle valid Braze Click Actions (brazeActions://).

    Parameters

    • url: string

      a valid URL, or a valid brazeActions URL with scheme brazeActions://v{versionInt}/{base64string}

    • Optional openLinkInNewTab: undefined | false | true

      Whether the URL should be opened in a new tab. Defaults to false.

    Returns void

hideContentCards

  • hideContentCards(parentNode?: Element | null): void
  • Hide any Braze content cards currently showing in the parent node, or if none is provided, any content cards in the page. This method will appropriately clean up any retained resources and also display the hiding animation, and so should be used instead of manually removing content cards HTML from the DOM.

    Parameters

    • Optional parentNode: Element | null

      The HTML node that denotes the parent of the content cards to be hidden. If null/undefined, all content cards on the page will be hidden.

    Returns void

initialize

  • Initializes this braze instance with your API key. This method must be called before other Braze methods are invoked, and is part of the default loading snippets. Subsequent calls will be ignored until 'destroy` is called.

    Parameters

    Returns boolean

    • Whether or not the braze instance has been successfully initialized. Reasons for returning false include a missing API key/base URL, user opt out, and ignored crawler bot activity.

isDisabled

  • isDisabled(): boolean
  • Getter method to determine if the SDK is disabled based on whether the cookie set by disableSdk exists

    Returns boolean

isPushBlocked

  • isPushBlocked(): boolean | undefined
  • Returns boolean | undefined

    Whether or not the user has blocked push. If the user has blocked push, they cannot be prompted to register again, and must manually remove the block in order to receive push. Returns undefined if the SDK has not been initialized.

isPushPermissionGranted

  • isPushPermissionGranted(): boolean | undefined
  • Tests whether the user has given this browser push permission (they may still be unsubscribed from push via User.setPushNotificationSubscriptionType). A true value essentially means that requestPushPermission may be called without the user being prompted. Useful for migrating existing non-Braze push registrations to Braze.

    Returns boolean | undefined

    Whether or not the user has granted push permission. If this returns true, requestPushPermission may be called without the user being prompted. If this returns false, requestPushPermission may prompt the user (if isPushSupported returns true) or do nothing (if isPushSupported returns false). Returns undefined if the SDK has not been initialized.

isPushSupported

  • isPushSupported(): boolean | undefined
  • The W3C Push API is partially supported across the browser landscape. This method allows you to programmatically determine whether push is supported in the current browser, and whether to show push-related user class elements to the user.

    Returns boolean | undefined

    Whether or not push is supported in this environment. Returns undefined if the SDK has not been initialized.

logCardClick

  • logCardClick(card: Card, forContentCards?: undefined | false | true): boolean
  • Logs that the user clicked the given card. This is done automatically when you use Braze's display module and should only be called if you're bypassing that and manually building the DOM for displaying the cards in your own code.

    Parameters

    • card: Card

      the Card object that received a click

    • Optional forContentCards: undefined | false | true

      whether to log this as a content cards event (as opposed to the legacy news feed)

    Returns boolean

    Whether or not the event was successfully logged (to be flushed later).

logCardDismissal

  • logCardDismissal(card: Card): boolean
  • Logs that the user dismissed the given card. This is done automatically when you use Braze's display module and should only be called if you're bypassing that and manually building the DOM for displaying the cards in your own code.

    Parameters

    • card: Card

      the Card object that received a dismissal

    Returns boolean

    Whether or not the event was successfully logged (to be flushed later).

logCardImpressions

  • logCardImpressions(cards: Card[], forContentCards?: undefined | false | true): boolean
  • Logs that the user saw the given cards. This is done automatically when you use Braze's display module and should only be called if you're bypassing that and manually building the DOM for displaying the cards in your own code.

    Parameters

    • cards: Card[]

      array of Card objects that received impressions

    • Optional forContentCards: undefined | false | true

      whether to log this as a content cards event (as opposed to the legacy news feed)

    Returns boolean

    Whether or not the event was successfully logged (to be flushed later).

logContentCardClick

  • logContentCardClick(contentCard: Card): boolean
  • A convenient method to log when user clicks on a Content Card. This method is equivalent to calling [logCardClick method with forContentCards param set to true. This is done automatically when you use Braze's display module and should only be called if you're bypassing that and manually building the DOM for displaying content cards in your own code.

    Parameters

    • contentCard: Card

      the Card object that received a click

    Returns boolean

    Whether or not the event was successfully logged (to be flushed later).

logContentCardImpressions

  • logContentCardImpressions(contentCards: Card[]): boolean
  • A convenient method to log that the user saw the given Content Cards. This method is equivalent to calling [logCardImpressions method with forContentCards param set to true. This is done automatically when you use Braze's display module and should only be called if you're bypassing that and manually building the DOM for displaying content cards in your own code.

    Parameters

    • contentCards: Card[]

      array of Card objects that received impressions

    Returns boolean

    Whether or not the event was successfully logged (to be flushed later).

logCustomEvent

  • logCustomEvent(eventName: string, eventProperties?: undefined | object): boolean
  • Reports that the current user performed a custom named event.

    Parameters

    • eventName: string

      The identifier for the event to track. Value is limited to 255 characters in length, cannot begin with a $, and can only contain alphanumeric characters and punctuation.

    • Optional eventProperties: undefined | object

      Hash of properties for this event. Keys are limited to 255 characters in length, cannot begin with a $, and can only contain alphanumeric characters and punctuation. Values can be numeric, boolean, Date objects, strings 255 characters or shorter, or nested objects whose values can be numeric, boolean, Date objects, arrays, strings, or null. Total size of event properties cannot exceed 50KB.

    Returns boolean

    Whether or not the event was successfully logged (to be flushed later).

logFeatureFlagImpression

  • logFeatureFlagImpression(featureFlagId: string): boolean | undefined
  • Logs impression for a given feature flag.

    Parameters

    • featureFlagId: string

      ID of the feature flag that has received the impression.

    Returns boolean | undefined

    • Whether or not the impression was successfully logged. Returns undefined if the SDK has not been initialized.

logFeedDisplayed

  • logFeedDisplayed(): void
  • Logs that the news feed was displayed. This is done automatically when you use Braze's UI and should only be called if you're bypassing that and manually building the class for displaying the cards in your own code.

    Returns void

logInAppMessageButtonClick

  • Logs that the user clicked the given in-app message button. This is done automatically when the user clicks on a button in a message generated by showInAppMessage, and should only be called if you're bypassing that method and manually displaying the message in your own code.

    Parameters

    Returns boolean

    Whether or not the event was successfully logged (to be flushed later).

logInAppMessageClick

  • Logs that the user clicked the given in-app message. This is done automatically when the user clicks on a message generated by showInAppMessage, and should only be called if you're bypassing that method and manually displaying the message in your own code.

    Parameters

    Returns boolean

    Whether or not the event was successfully logged (to be flushed later).

logInAppMessageHtmlClick

  • logInAppMessageHtmlClick(inAppMessage: HtmlMessage, buttonId?: undefined | string, url?: undefined | string): boolean
  • Logs that the user clicked on a link in an html in-app message. This is done automatically when the user clicks on a message generated by showInAppMessage, and should only be called if you're bypassing that method and manually displaying the message in your own code.

    Parameters

    • inAppMessage: HtmlMessage

      The message that was clicked

    • Optional buttonId: undefined | string

      A button id to associate this click with for analytics

    • Optional url: undefined | string

      The url that was clicked

    Returns boolean

    Whether or not the event was successfully logged (to be flushed later).

logInAppMessageImpression

  • Logs that the user saw the given in-app message. This is performed automatically when you use showInAppMessage, and should only be called if you're bypassing that method and manually displaying the message in your own code.

    Parameters

    Returns boolean

    Whether or not the event was successfully logged (to be flushed later).

logPurchase

  • logPurchase(productId: string, price: number, currencyCode?: undefined | string, quantity?: undefined | number, purchaseProperties?: undefined | object): boolean
  • Reports that the current user made an in-app purchase. Useful for tracking and segmenting users.

    Parameters

    • productId: string

      A string identifier for the product purchased, e.g. an SKU. Value is limited to 255 characters in length, cannot begin with a $, and can only contain alphanumeric characters and punctuation.

    • price: number

      The price paid. Base units depend on the currency. As an example, USD should be reported as Dollars.Cents, whereas JPY should be reported as a whole number of Yen. All provided values will be rounded to two digits with toFixed(2)

    • Optional currencyCode: undefined | string

      Default USD. Currencies should be represented as an ISO 4217 currency code. Supported currency symbols include: AED, AFN, ALL, AMD, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BRL, BSD, BTC, BTN, BWP, BYR, BZD, CAD, CDF, CHF, CLF, CLP, CNY, COP, CRC, CUC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EEK, EGP, ERN, ETB, EUR, FJD, FKP, GBP, GEL, GGP, GHS, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, IMP, INR, IQD, IRR, ISK, JEP, JMD, JOD, JPY, KES, KGS, KHR, KMF, KPW, KRW, KWD, KYD, KZT, LAK, LBP, LKR, LRD, LSL, LTL, LVL, LYD, MAD, MDL, MGA, MKD, MMK, MNT, MOP, MRO, MTL, MUR, MVR, MWK, MXN, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PAB, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SDG, SEK, SGD, SHP, SLL, SOS, SRD, STD, SVC, SYP, SZL, THB, TJS, TMT, TND, TOP, TRY, TTD, TWD, TZS, UAH, UGX, USD, UYU, UZS, VEF, VND, VUV, WST, XAF, XAG, XAU, XCD, XDR, XOF, XPD, XPF, XPT, YER, ZAR, ZMK, ZMW, and ZWL. Any other provided currency symbol will result in a logged warning and no other action taken by the SDK.

    • Optional quantity: undefined | number

      Default 1. The quantity of items purchased expressed as a whole number. Must be at least 1 and at most 100.

    • Optional purchaseProperties: undefined | object

      Hash of properties for this purchase. Keys are limited to 255 characters in length, cannot begin with a $, and can only contain alphanumeric characters and punctuation. Values can be numeric, boolean, Date objects, strings 255 characters or shorter, or nested objects whose values can be numeric, boolean, Date objects, arrays, strings, or null. Total size of purchase properties cannot exceed 50KB.

    Returns boolean

    Whether or not the purchase was successfully attached to the session (to be flushed later).

openSession

  • openSession(): void
  • Opens a new session, or resumes the previous session if this browser had activity within the sessionTimeoutInSeconds value. When a new session is opened, this refreshes In-App Messages. Content Cards are refreshed automatically if the subscribeToContentCardsUpdates has been registered prior to openSession. If the user has previously granted the site permission to send push, automatically sends the push registration to the Braze backend.

    Be sure to call openSession at the end of your initialization code section, after any calls to changeUser or subscribing to Content Cards, In-App Message, and Feature Flag updates. Calling openSession before changeUser may result in a second session start event.

    Returns void

refreshFeatureFlags

  • refreshFeatureFlags(successCallback?: undefined | (() => void), errorCallback?: undefined | (() => void)): void
  • Requests an immediate refresh of feature flags from Braze servers. By default, feature flags are refreshed when a new session starts. If you want to refresh feature flags from the server at another time you must call this function.

    Parameters

    • Optional successCallback: undefined | (() => void)

      Callback that is invoked when the feature flags refresh request has been successfully completed. This callback is useful for determining when a request has completed regardless of whether new feature flags were returned.

    • Optional errorCallback: undefined | (() => void)

      Callback that is invoked when an error occurs during the refresh.

    Returns void

removeAllSubscriptions

  • removeAllSubscriptions(): void
  • Remove all event subscriptions.

    Returns void

removeSubscription

  • removeSubscription(subscriptionGuid: string): void
  • Remove an event subscription that you previously subscribed to.

    Parameters

    • subscriptionGuid: string

      The identifier of the subscription you wish to remove, returned by the method you initially used to create it.

    Returns void

requestContentCardsRefresh

  • requestContentCardsRefresh(successCallback?: undefined | (() => void), errorCallback?: undefined | (() => void)): void
  • Requests an immediate refresh of content cards from Braze servers. By default, content cards are refreshed when a new session opens (see 'openSession` for more details), and when the user refreshes content cards manually via the refresh button. If you want to refresh content cards from the server at another time you must call this function.

    Parameters

    • Optional successCallback: undefined | (() => void)

      Callback that is invoked when the content cards refresh request has been successfully completed. You should use subscribeToContentCardsUpdates to be notified of new cards. This callback is useful for determining when a request has completed regardless of whether new cards were returned.

    • Optional errorCallback: undefined | (() => void)

      Callback that is invoked when an error occurs during the refresh.

    Returns void

requestFeedRefresh

  • requestFeedRefresh(): void
  • Requests an immediate refresh of the news feed from Braze servers. By default, the news feed is refreshed on showFeed (when stale - see showFeed for details). If you want to refresh the feed from the server at another time you must call this function. Results of this refresh are reported asynchronously to subscriptions created via 'subscribeToFeedUpdates` .

    Returns void

requestImmediateDataFlush

  • requestImmediateDataFlush(callback?: undefined | ((success: boolean) => void)): void
  • By default, data logged to Braze through the SDK is queued locally (in HTML 5 localStorage when available, and in memory otherwise) and sent to Braze's servers asynchronously on a regular interval (10 seconds when localStorage is available and not routinely cleared due to browser privacy features, otherwise 3 seconds). This is done to optimize network usage and provide resiliency against network or server outages. This method bypasses the interval and immediately flushes queued data.

    Parameters

    • Optional callback: undefined | ((success: boolean) => void)

      Invoked when the flush completes with a boolean parameter that returns whether or not the flush was successful. If the flush is unsuccessful, pending data will be flushed during the next successful flush.

    Returns void

requestPushPermission

  • requestPushPermission(successCallback?: undefined | ((endpoint: string, publicKey: string, userAuth: string) => void), deniedCallback?: undefined | ((temporaryDenial: boolean) => void)): void
  • Register this browser environment to receive web push for this user. Supports browsers which implement the W3C Push API (browsers in which isPushSupported returns true). If push is supported and the user is not already subscribed, this method will cause the browser to immediately request push permission from the user.

    In order to properly use this feature, there are some integration steps required on your end:

    • Your site must be https
    • Create a service-worker.js file with the content below and place it in the root directory of your website:
    self.importScripts('https://js.appboycdn.com/web-sdk/{{VERSION}}/service-worker.js');

    For more details, see Our Product Documentation.

    Parameters

    • Optional successCallback: undefined | ((endpoint: string, publicKey: string, userAuth: string) => void)

      When the user subscribes to push successfully this callback will be invoked with the user's endpoint, public key, and user auth key (endpoint, publicKey, userAuth).

    • Optional deniedCallback: undefined | ((temporaryDenial: boolean) => void)

      If push permission is denied or an error is encountered while registering, this callback will be invoked. If the denial is temporary, it will be invoked with a parameter of true - otherwise it will be invoked with a parameter of false.

    Returns void

setLogger

  • setLogger(loggerFunction: (message: string) => void): void
  • By default, Braze logs to the browser console. Call this method to set a custom log action and enable debug-level log statements.

    Parameters

    • loggerFunction: (message: string) => void

      A function to invoke with log messages. Should accept a single string parameter for message.

        • (message: string): void
        • Parameters

          • message: string

          Returns void

    Returns void

setSdkAuthenticationSignature

  • setSdkAuthenticationSignature(signature: string): boolean
  • Sets the signature to be used to authenticate the current user. You can also set the signature when calling changeUser. This signature will only have an effect if the enableSdkAuthentication initialization option is set to true.

    Parameters

    • signature: string

      The signature to add to network requests to authenticate the current user.

    Returns boolean

    Whether or not the signature is valid.

showContentCards

  • showContentCards(parentNode?: Element | null, filterFunction?: undefined | ((cards: Card[]) => Card[])): void
  • Display the user's content cards.

    Parameters

    • Optional parentNode: Element | null

      The HTML node to render the content cards into. If null/undefined, the content cards will be rendered in fixed position over the right-hand side of the page and appended to the <body> node. If the parent node already has a Braze content cards view as a direct descendant, the existing content cards will be replaced.

    • Optional filterFunction: undefined | ((cards: Card[]) => Card[])

      A filter/sort function for cards displayed in this view. Invoked with the array of Card objects, sorted by {pinned, date}. Expected to return an array of sorted Card objects to render for this user. If omitted, all cards will be displayed.

    Returns void

showFeed

  • showFeed(parentNode?: Element | null, cards?: Card[] | null, allowedCategories?: string[]): void
  • Display the user's news feed.

    Parameters

    • Optional parentNode: Element | null

      The HTML node to render the news feed into. If null/undefined, the feed will be rendered in fixed position over the right-hand side of the page and appended to the <body> node. If the parent node already has an Braze news feed as a direct descendant, the existing feed will be replaced.

    • Optional cards: Card[] | null

      A static set of cards to Each item in this Array should be a Card descendant. If this parameter is null/undefined, all unexpired cards from the last news feed refresh will be used automatically, a feed refresh will be kicked off automatically if the cached cards are more than 1 minute old, and the feed will automatically update when new cards are received while it is still showing. If you provide an explicit set of cards by using this parameter, no action will be taken when new cards are received, and you must subscribe to feed updates yourself with subscribeToFeedUpdates and request updates with requestFeedRefresh if you want to update this feed with new cards.

    • Optional allowedCategories: string[]

      A set of categories to filter cards to. Each item in this Array should be a card category as set in the Braze dashboard. If omitted, all cards will be displayed.

    Returns void

showInAppMessage

  • showInAppMessage(inAppMessage: InAppMessage | ControlMessage, parentNode?: Element | null, onDisplayCallback?: undefined | (() => void)): boolean
  • Display a given in-app message.

    Parameters

    • inAppMessage: InAppMessage | ControlMessage

      The message to

    • Optional parentNode: Element | null

      The HTML node to render the in-app message into. If null/undefined, the message will be rendered appended within the <body> node.

    • Optional onDisplayCallback: undefined | (() => void)

      Optional callback to invoke once the message is on the screen.

    Returns boolean

    Whether or not the message was displayed (or, in the case of control messages, logged to Braze servers).

subscribeToContentCardsUpdates

  • subscribeToContentCardsUpdates(subscriber: (cards: ContentCards) => void): string | undefined
  • Subscribe to content cards updates. The subscriber callback will be called whenever content cards are updated. This method should be called before calling openSession.

    Parameters

    • subscriber: (cards: ContentCards) => void

      The callback function to handle new cards. This function will be called with a ContentCards object which includes all currently available Card objects. If you want to be notified when a refresh has completed regardless of whether new cards are available, you should use the successCallback of requestContentCardsRefresh.

    Returns string | undefined

    The identifier of the subscription created. This can be passed to removeSubscription to cancel the subscription. Returns undefined if the SDK has not been initialized.

subscribeToFeatureFlagsUpdates

  • subscribeToFeatureFlagsUpdates(subscriber: (featureFlags: FeatureFlag[]) => void): string | undefined
  • Subscribe to feature flag updates. The subscriber callback will be called whenever feature flags are updated. This method should be called before calling openSession.

    Parameters

    • subscriber: (featureFlags: FeatureFlag[]) => void

      The callback function to handle new feature flags. This function is always called first with the available cached list of FeatureFlag objects, and will also be called when feature flag updates are available. If there is a failure in receiving updates, this function will be called with the cached list of FeatureFlag objects. If you want to be notified when a refresh has completed regardless of whether new feature flags are available, you should use the successCallback of refreshFeatureFlags.

    Returns string | undefined

    The identifier of the subscription created. This can be passed to removeSubscription to cancel the subscription. Returns undefined if the SDK has not been initialized.

subscribeToFeedUpdates

  • subscribeToFeedUpdates(subscriber: (feed: Feed) => void): string | undefined
  • Subscribe to news feed updates. The subscriber callback will be called whenever the news feed is updated.

    Parameters

    • subscriber: (feed: Feed) => void

      The callback function to handle new cards. This function will be called with a Feedobject which includes all Card objects currently in the feed.

        • (feed: Feed): void
        • Parameters

          Returns void

    Returns string | undefined

    The identifier of the subscription created. This can be passed to removeSubscription to cancel the subscription. Returns undefined if the SDK has not been initialized.

subscribeToInAppMessage

  • Subscribe to receive in-app messages. The subscriber callback will be called whenever a new in-app message is triggered. This method should be called before calling openSession. If you are using the build of Braze's library with UI, the most basic usage of this would be

    braze.subscribeToInAppMessage(function(inAppMessage) {
      braze.showInAppMessage(inAppMessage);
    });

    Parameters

    Returns string | undefined

    The identifier of the subscription created. This can be passed to 'removeSubscription` to cancel the subscription. Returns undefined if the SDK has not been initialized.

subscribeToSdkAuthenticationFailures

  • subscribeToSdkAuthenticationFailures(subscriber: (error: { errorCode: number; reason?: undefined | string; signature?: undefined | string; userId?: undefined | string }) => void): string | undefined
  • Subscribe to be notified of network request failures that occured due to an SDK Authentication error. This method can be used to determine when to call setSdkAuthenticationSignature to provide the SDK with a new signature. If you do not have SDK Authentication enabled on the Braze dashboard, this subscription will never be invoked.

    Parameters

    • subscriber: (error: { errorCode: number; reason?: undefined | string; signature?: undefined | string; userId?: undefined | string }) => void

      The subscriber function that is invoked whenever an SDK Authentication error occurs. It is invoked with an object containing the errorCode, reason for the error, the userId of the request (if the user is not anonymous), and the authentication signature that caused the error.

        • (error: { errorCode: number; reason?: undefined | string; signature?: undefined | string; userId?: undefined | string }): void
        • Parameters

          • error: { errorCode: number; reason?: undefined | string; signature?: undefined | string; userId?: undefined | string }
            • errorCode: number
            • Optional reason?: undefined | string
            • Optional signature?: undefined | string
            • Optional userId?: undefined | string

          Returns void

    Returns string | undefined

    The identifier of the subscription created. This can be passed to 'removeSubscription` to cancel the subscription. Returns undefined if the SDK has not been initialized.

toggleContentCards

  • toggleContentCards(parentNode?: Element | null, filterFunction?: undefined | ((cards: Card[]) => Card[])): void
  • Toggle the display of Braze content cards, showing them if they are not shown, and hiding them if they are. If you wish to display multiple content cards feeds on a page simultaneously, you should use showContentCards and hideContentCards to show/hide each feed individually instead of this method.

    Parameters

    • Optional parentNode: Element | null

      The HTML node to render the content cards into. If null/undefined, the content cards will be rendered in fixed position over the right-hand side of the page and appended to the <body> node. If the parent node already has a Braze content cards view as a direct descendant, the existing content cards will be replaced.

    • Optional filterFunction: undefined | ((cards: Card[]) => Card[])

      A filter/sort function for cards displayed in this view. Invoked with the array of Card objects, sorted by {pinned, date}. Expected to return an array of sorted Card objects to render for this user. If omitted, all cards will be displayed.

    Returns void

toggleFeed

  • toggleFeed(parentNode?: Element | null, cards?: Card[] | null, allowedCategories?: string[]): void
  • Toggle the Braze news feed, creating it if it does not exist, and destroying it if it does.

    Parameters

    • Optional parentNode: Element | null

      The HTML node to render the news feed into. If null/undefined, the feed will be rendered in fixed position over the right-hand side of the page and appended to the <body> node. If the parent node already has an Braze news feed as a direct descendant, the existing feed will be replaced.

    • Optional cards: Card[] | null

      A static set of cards to Each item in this Array should be a Card descendant. If this parameter is null/undefined, all unexpired cards from the last news feed refresh will be used automatically, a feed refresh will be kicked off automatically if the cached cards are more than 1 minute old, and the feed will automatically update when new cards are received while it is still showing. If you provide an explicit set of cards by using this parameter, no action will be taken when new cards are received, and you must subscribe to feed updates yourself with subscribeToFeedUpdates and request updates with requestFeedRefresh if you want to update this feed with new cards.

    • Optional allowedCategories: string[]

      A set of categories to filter cards to. Each item in this Array should be a card category as set in the Braze dashboard. If omitted, all cards will be displayed.

    Returns void

toggleLogging

  • toggleLogging(): void
  • By default, Braze silences its logging to prevent spamming production js consoles. Call this method to toggle logging.

    Returns void

unregisterPush

  • unregisterPush(successCallback?: undefined | (() => void), errorCallback?: undefined | (() => void)): void
  • Unregisters push notifications on this browser. Note that for Safari, Apple does not offer any unsubscribe mechanism, so on Safari this method leaves the user with push permission granted and simply sets their subscription status to unsubscribed.

    Parameters

    • Optional successCallback: undefined | (() => void)

      When the unsubscribe is successfully recorded and processed by Braze, this callback will be invoked.

    • Optional errorCallback: undefined | (() => void)

      If the unsubscribe fails for unknown reasons, this callback will be invoked.

    Returns void

wipeData

  • wipeData(): void
  • Removes all locally stored SDK data, causing the user to be seen in subsequent calls as a new anonymous user on a new device.

    Returns void