Module: appboy

This is the public interface for the Braze Web SDK. To get started right away, check out our Web SDK github repository.

Members

<static, readonly> ab.DeviceProperties :string

Enum to represent the whitelistable set of device properties. By default, all properties are collected. See the devicePropertyWhitelist option of appboy.initialize for more info.

Type:
  • string
Properties:
Name Type Default Description
BROWSER string browser

The name of the browser - e.g. "Chrome"

BROWSER_VERSION string browserVersion

The version of the browser - e.g. "59.234.1234"

OS string os

The name of the operating system - e.g. "Android"

RESOLUTION string resolution

The screen resolution of the device - e.g. "1024x768"

LANGUAGE string language

The language the browser is set to use - e.g. "en-us"

TIME_ZONE string timeZone

The time zone of the device - e.g. "America/New_York"

USER_AGENT string userAgent

The user agent string of the browser - see @{link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent this link} for more info

Methods

<static> changeUser(userId)

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 become orphaned and will not be associated with any future users. These orphaned users are not considered in your user counts and will not be messaged.

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:
Name Type Description
userId string

A unique identifier for this user.

<static> destroy()

Destroys this appboy instance, destroying all subscription callbacks and releasing member variables which retain memory.

<static> getCachedContentCards() → {ab.ContentCards}

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

Returns:
  • An ab.ContentCards object which includes all currently available ab.Card objects from the last content cards refresh.

The Content Cards feature is currently in closed beta testing. If you're interested in joining the beta, please reach out to your Customer Success Manager or Account Manager.

Type
ab.ContentCards

<static> getCachedFeed() → {ab.Feed}

Get all unexpired cards from the last news feed refresh.

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

<static> getDeviceId(callback)

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:

appboy.getDeviceId(function(deviceId) {
   console.log('The device id is ' + deviceId);
});
Parameters:
Name Type Description
callback function

Asynchronous callback - this will be invoked with the deviceId.

<static> getUser() → {ab.User}

Returns:

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.

Type
ab.User

<static> initialize(apiKey, options) → {Boolean}

Initializes this appboy 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:
Name Type Argument Description
apiKey string

Your app's Braze API Key. Your API keys can be found here.

options object <optional>

Optional configuration options. Supported options:

  • allowCrawlerActivity - 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 datapoints, 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.
  • appVersion - 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.
  • baseUrl - If Braze has provided you with a custom, client-specific endpoint, (for data isolation and reliability purposes), use this option to configure the Braze Web SDK to use that endpoint, for example appboy.initialize('YOUR-API-KEY-HERE', {baseUrl: 'https://example.appboy.eu/api/v3'})
  • devicePropertyWhitelist - By default, the Braze SDK automatically detects and collects all device properties in ab.DeviceProperties. To override this behavior, provide an array of ab.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.
  • noCookies - 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.
  • doNotLoadFontAwesome - Braze uses FontAwesome 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.
  • enableHtmlInAppMessages - By default, the Braze Web SDK does not enable HTML in-app messages, as they allow Braze dashboard users unfettered javascript access to your site. To indicate that you trust the Braze dashboard users to write non-malicious HTML in-app messages, set this property to true.
  • enableLogging - 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 appboy.setLogger() before you release your page to production.
  • localization - 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 ab.User.setLanguage for setting the language you use within the Braze dashboard to localize your own messaging content.
  • minimumIntervalBetweenTriggerActionsInSeconds - 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.
  • openInAppMessagesInNewTab - 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.
  • openCardsInNewTab - By default, links from ab.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.
  • requireExplicitInAppMessageDismissal - By default, when an in-app message is showing, 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.
  • safariWebsitePushId - 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")
  • serviceWorkerLocation - 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, registerAppboyPushMessages MAY ONLY BE CALLED from web pages that start with http://yoursite.com/mycustompath/.
  • sessionTimeoutInSeconds - 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.
Returns:
  • Whether or not the appboy instance has been successfully initialized. Reasons for returning false include a missing API key, user opt out, and ignored crawler bot activity.
Type
Boolean

<static> isPushBlocked() → {boolean}

Returns:

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.

Type
boolean

<static> isPushGranted(yesCallback, noCallback)

DEPRECATED - Tests whether the user has given this browser push permission (they may still be unsubscribed from push via ab.User.setPushNotificationSubscriptionType). A true value essentially means that appboy.registerAppboyPushMessages may be called without the user being prompted. Useful for migrating existing non-Braze push registrations to Braze.

Parameters:
Name Type Description
yesCallback function

Invoked if the user has granted push access on this browser

noCallback function

Invoked if the user has not granted push access on this browser

Deprecated:
  • This function inappropriately reports whether or not the browser *currently* has an active registered push subscription, and does not answer the intended permissions question of whether the user has granted the browser push permissions. Please use appboy.isPushPermissionGranted instead. This function WILL BE REMOVED.

<static> isPushPermissionGranted() → {boolean}

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

Returns:

Whether or not the user has granted push permission. If this returns true, appboy.registerAppboyPushMessages may be called without the user being prompted. If this returns false, appboy.registerAppboyPushMessages may prompt the user (if appboy.isPushSupported returns true) or do nothing (if appboy.isPushSupported returns false)

Type
boolean

<static> isPushSupported() → {boolean}

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 interface elements to the user.

Returns:

Whether or not push is supported in this environment.

Type
boolean

<static> logCardClick(card, forContentCards) → {boolean}

Logs that the user clicked the given card. This is done automatically when you use Appboy'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:
Name Type Argument Description
card string

the ab.Card object that received a click

forContentCards boolean <optional>

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

Returns:

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

Type
boolean

<static> logCardDismissal(card) → {boolean}

Logs that the user dismissed the given card. This is done automatically when you use Appboy'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:
Name Type Description
card string

the ab.Card object that received a dismissal

Returns:

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

Type
boolean

<static> logCardImpressions(cards, forContentCards) → {boolean}

Logs that the user saw the given cards. This is done automatically when you use Appboy'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:
Name Type Argument Description
cards Array

array of ab.Card objects that received impressions

forContentCards boolean <optional>

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

Returns:

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

Type
boolean

<static> logContentCardsDisplayed()

Logs that the content cards were displayed. This is done automatically when you use Appboy's display module and should only be called if you're bypassing that and manually building the interface for displaying the cards in your own code.

The Content Cards feature is currently in closed beta testing. If you're interested in joining the beta, please reach out to your Customer Success Manager or Account Manager.

<static> logCustomEvent(eventName, eventProperties) → {boolean}

Reports that the current user performed a custom named event.

Parameters:
Name Type Argument Description
eventName string

The identifier for the event to track. Best practice is to track generic events useful for segmenting, instead of specific user actions (i.e. track watched_sports_video instead of watched_video_adrian_peterson_td_mnf). Value is limited to 255 characters in length, cannot begin with a $, and can only contain alphanumeric characters and punctuation.

eventProperties object <optional>

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, or strings 255 characters or shorter.

Returns:

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

Type
boolean

<static> logFeedDisplayed()

Logs that the news feed was displayed. This is done automatically when you use Appboy's display module and should only be called if you're bypassing that and manually building the interface for displaying the cards in your own code.

<static> logInAppMessageButtonClick(button, inAppMessage) → {boolean}

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 appboy.display.showInAppMessage, and should only be called if you're bypassing that method and manually displaying the message in your own code.

Parameters:
Name Type Description
button ab.InAppMessage.Button

The button clicked

inAppMessage ab.InAppMessage

The message this button belongs to

Returns:

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

Type
boolean

<static> logInAppMessageClick(inAppMessage) → {boolean}

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

Parameters:
Name Type Description
inAppMessage ab.InAppMessage
Returns:

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

Type
boolean

<static> logInAppMessageHtmlClick(inAppMessage, buttonId, url) → {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 appboy.display.showInAppMessage, and should only be called if you're bypassing that method and manually displaying the message in your own code.

Parameters:
Name Type Argument Description
inAppMessage ab.HtmlMessage

The message that was clicked

buttonId string <optional>

A button id to associate this click with for analytics

url string <optional>

The url that was clicked

Returns:

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

Type
boolean

<static> logInAppMessageImpression(inAppMessage) → {boolean}

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

Parameters:
Name Type Description
inAppMessage ab.InAppMessage | ab.ControlMessage
Returns:

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

Type
boolean

<static> logPurchase(productId, price, currencyCode, quantity, purchaseProperties) → {boolean}

Reports that the current user made an in-app purchase. Useful for tracking and segmenting users.

Parameters:
Name Type Argument Default Description
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 float

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)

currencyCode string <optional>
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.

quantity integer <optional>
1

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

purchaseProperties object <optional>

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, or strings 255 characters or shorter.

Returns:

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

Type
boolean

<static> openSession()

Opens a new session, or resumes the previous session if this browser had activity within the last 30 minutes. When a new session is opened, syncs triggered In-App Messages and Content Cards. If the user has previously granted the site permission to send push, automatically sends the push registration to the Braze backend.

<static> registerAppboyPushMessages(successCallback, deniedCallback)

Register this browser environment to receive web push for this user. Supports browsers which implement the W3C Push API (browsers in which appboy.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/2.3/service-worker.js');

For more details, see Our Product Documentation.

Parameters:
Name Type Argument Description
successCallback function <optional>

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

deniedCallback function <optional>

If push permission is denied, 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.

<static> removeAllSubscriptions()

Remove all event subscriptions.

<static> removeSubscription(subscriptionGuid)

Remove an event subscription that you previously subscribed to.

Parameters:
Name Type Description
subscriptionGuid string

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

<static> requestContentCardsRefresh()

Requests an immediate refresh of content cards from Appboy servers. By default, content cards are refreshed when a new session opens (see appboy.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.

The Content Cards feature is currently in closed beta testing. If you're interested in joining the beta, please reach out to your Customer Success Manager or Account Manager.

<static> requestFeedRefresh()

Requests an immediate refresh of the news feed from Braze servers. By default, the news feed is refreshed on appboy.display.showFeed (when stale - see appboy.display.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.

<static> requestImmediateDataFlush()

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 available, otherwise 3 seconds). This is done to optimize network usage and provide resiliancy against network or server outages. This method bypasses the interval and immediately flushes queued data.

<static> resumeWebTracking()

Removes the cookie set by stopWebTracking, causing subsequent calls to the Braze Web SDK to function. You must call initialize after calling this method before calling subsequent methods.

<static> setLogger(loggerFunction)

By default, Braze logs to the browser console. Call this method to set a custom log action and enable debug-level log statements.

Parameters:
Name Type Description
loggerFunction function

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

<static> stopWebTracking()

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.

<static> submitFeedback(replyToEmail, message, isReportingABug, successCallback, errorCallback) → {boolean}

DEPRECATED - Submits a piece of feedback to the Braze feedback center so that it can be handled in the Braze dashboard. The request to submit feedback is made immediately, however, this method does not block and will return as soon as the feedback request is placed on the network queue. To be notified when the network request succeeds or fails, use the successCallback and errorCallback params.

Parameters:
Name Type Argument Description
replyToEmail string

The email address to send feedback replies to.

message string

The message from the user. Must be non-null and non-empty.

isReportingABug boolean

Flag indicating whether or not the feedback describes a bug, or is merely a suggestion/question.

successCallback function <optional>

When the feedback is successfully recorded and processed by Braze, this callback will be invoked with (replyToEmail, message, isReportingABug) as parameters.

errorCallback function <optional>

If the feedback request fails (e.g. due to network conditions or service outages), this callback will be invoked with (replyToEmail, message, isReportingABug) as parameters.

Deprecated:
  • Since Web SDK 2.1.0, the feedback feature is deprecated, and will be removed in a future SDK release.
Returns:

Whether or not the feedback was successfully queued for delivery.

Type
boolean

<static> subscribeToContentCardsUpdates(subscriber) → {string}

Subscribe to content cards updates. The subscriber callback will be called whenever content cards are updated.

Parameters:
Name Type Description
subscriber function

The callback function to handle new cards. This function will be called with an ab.ContentCards object which includes all currently available ab.Card objects.

Returns:

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

The Content Cards feature is currently in closed beta testing. If you're interested in joining the beta, please reach out to your Customer Success Manager or Account Manager.

Type
string

<static> subscribeToFeedUpdates(subscriber) → {string}

Subscribe to news feed updates. The subscriber callback will be called whenever the news feed is updated.

Parameters:
Name Type Description
subscriber function

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

Returns:

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

Type
string

<static> subscribeToNewInAppMessages(subscriber) → {string}

Subscribe to receive in-app messages. The subscriber callback will be called whenever new in-app messages are triggered. If you are using the build of Braze's library with UI, the most basic usage of this would be

appboy.subscribeToNewInAppMessages(function(inAppMessages) {
  appboy.display.showInAppMessage(inAppMessages[0]);
  return inAppMessages.slice(1);
});
Parameters:
Name Type Description
subscriber function

The callback function to handle new in-app messages. This function will be called with an array of all currently unhandled ab.InAppMessage or ab.ControlMessage objects. If you are using the build of Braze's library with UI, you may wish to call appboy.display.showInAppMessage with one or more messages. This function should return an array of any messages that you wish to remain unhandled and retained until the next time subscriber is called.

Returns:

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

Type
string

<static> toggleAppboyLogging()

By default, Braze silences its logging to prevent spamming production js consoles. Call this method to toggle logging.

<static> trackLocation()

Causes the Braze Web SDK to begin continuously collecting the user's location while your website is visible in the foreground of their browser, for the duration of this page load. This will cause the browser to request permission from the user if they have not already granted or denied it.

<static> unregisterAppboyPushMessages(successCallback, errorCallback)

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:
Name Type Argument Description
successCallback function <optional>

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

errorCallback function <optional>

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

<static> wipeData()

Removes all locally stored SDK data, causing the user to be seen in subsequent calls as a new anonymous user on a new device.