Filters

Web Full Reference

Using the Sample Web App

We provide a sample web app which demonstrates what Branch Metrics Web SDK can do. The online version can be found at https://cdn.branch.io/example.html. Alternatively, you can open example.html locally to for the same effect.

To modify this local web app, edit src/web/example.template.html first, and then run make, which will automatically update example.html. Refrain from manually editing example.html.

Requirements

This SDK requires native browser Javascript and has been tested in all modern browsers with sessionStorage capability. No 3rd party libraries are needed to make use of the SDK as is it 100% native Javascript.

Browser Specific Support

ChromeFirefoxSafariIE
9, 10, 11

Quick Install

Add the following script within your <head> tags:

Be sure to replace BRANCH KEY with your actual Branch Key found in your account dashboard.

<!doctype html>
<html>
   <head>
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title></title>
      <script>
         // load Branch
         (function(b,r,a,n,c,h,_,s,d,k){if(!b[n]||!b[n]._q){for(;s<_.length;)c(h,_[s++]);d=r.createElement(a);d.async=1;d.src="https://cdn.branch.io/branch-latest.min.js";k=r.getElementsByTagName(a)[0];k.parentNode.insertBefore(d,k);b[n]=h}})(window,document,"script","branch",function(b,r){b[r]=function(){b._q.push([r,arguments])}},{_q:[],_v:1},"addListener applyCode autoAppIndex banner closeBanner closeJourney creditHistory credits data deepview deepviewCta first getCode init link logout redeem referrals removeListener sendSMS setBranchViewData setIdentity track validateCode trackCommerceEvent logEvent disableTracking qrCode setRequestMetaData".split(" "), 0);
         // init Branch
         branch.init('key_live_YOUR_KEY_GOES_HERE');
      </script>
   </head>
   <body></body>
</html>

You can also get the sdk via npm or bower (branch-sdk)

Common.JS and RequireJS compatibility

In addition to working as a standalone library, the Branch SDK works great in CommonJS environments (browserify, webpack) as well as RequireJS environments (RequireJS/AMD). Just require('branch') or define(['branch'], function(branch) { ... }); to get started!

Initialization

You will need to create a Branch Metrics app to obtain your Branch Key (you will have the option to toggle between live and test modes).

Initializing the SDK is an asynchronous method with a callback, so it may seem as though you would need to place any method calls that will execute immediately inside the branch.init() callback. We've made it even easier than that, by building in a queue to the SDK! The only thing that is required is that branch.init() is called prior to any other methods. All SDK methods called are guaranteed to :

  1. be executed in the order that they were called, and
  2. wait to execute until the previous SDK method finishes.

Therefore, it is 100% allowable to do something like:

branch.init(...);
branch.banner(...);

If branch.init() fails, all subsequent branch methods will fail.

API Reference

init(branch_key, options, callback)

Parameters

ParameterTypeDescriptionRequired
branch_keystringYour Branch live key, or (deprecated) your app id.Y
optionsObject{ } See options table below.N
callbackfunctionCallback to read the session data.N

Adding the Branch script to your page automatically creates a window.branch object with all the external methods described below.

  • All calls made to Branch methods are stored in a queue, so even if the SDK is not fully instantiated, calls made to it will be queued in the order they were originally called.
  • If the session was opened from a referring link, data() will also return the referring link click as referring_link, which gives you the ability to continue the click flow.
  • The init function on the Branch object initiates the Branch session and creates a new user session, if it doesn't already exist, insessionStorage.

📘

Useful Tip

The init function returns a data object where you can read
the link the user was referred by.

Properties available in the options object:

KeyValueTypeRequired
branch_match_idThe current user's browser-fingerprint-id. The value of this parameter should be the same as the value of ?branch_match_id (automatically appended by Branch after a link click). _Only necessary if ?_branch_match_id is lost due to multiple redirects in your flow.stringN
branch_view_idIf you would like to test how Journeys render on your page before activating them, you can set the value of this parameter to the id of the view you are testing. Only necessary when testing a view related to a Journey.stringN
no_journeysWhen true, prevents Journeys from appearing on current page.booleanN
disable_entry_animationWhen true, prevents a Journeys entry animation.booleanN
disable_exit_animationWhen true, prevents a Journeys exit animation.booleanN
retriesValue specifying the number of times that a Branch API call can be re-attempted. Default 2.integerN
retry_delayAmount of time in milliseconds to wait before re-attempting a timed-out request to the Branch API. Default 200 ms.integer N
timeoutDuration in milliseconds that the system should wait for a response before considering any Branch API call to have timed out. Default 5000 ms.integerN
metadataKey-value pairs used to target Journeys users via the "is viewing a page with metadata key" filter.objectN
nonceA nonce value that will be added to branch-journey-cta injected script. Used to allow that script from a Content Security Policy.stringN
tracking_disabledtrue disables trackingbooleanN

Usage

branch.init(
    branch_key,
    options,
    callback (err, data),
);

Callback Format

callback(
     "Error message",
     {
          data_parsed:        { },                          // If the user was referred from a link, and the link has associated data, the data is passed in here.
          referring_identity: '12345',                      // If the user was referred from a link, and the link was created by a user with an identity, that identity is here.
          has_app:            true,                         // Does the user have the app installed already?
          identity:           'BranchUser',                 // Unique string that identifies the user
          ~referring_link:     'https://bnc.lt/c/jgg75-Gjd3' // The referring link click, if available.
     }
);

📘

Note

Branch.init must be called prior to calling any other Branch functions.

setRequestMetaData(key, value)

Parameters

ParameterTypeDescription
keystringCallback to read a user's browser-fingerprint-id.
valuestringThe value in the key-value pair.

Add additional metadata in the form of key-value pairs to every network request that is made by the Branch Web SDK. This metadata can be used for analytics, troubleshooting, or to enhance the data set sent with requests.

Usage

branch.setRequestMetadata("key","value");

setAPIUrl(url)

Parameters

ParameterTypeDescription
urlstringThe base URL that the Branch API uses.

Sets a custom base URL for all calls to the Branch API.

Usage

branch.setAPIUrl("https://api2.myhost.io");

data(callback)

Parameters

ParameterTypeDescriptionRequired
callbackfunctionCallback to read the session data.N

Returns the same session information and any referring data, asBranch.init, but does not require the app_id.

  • This is meant to be called after Branch.init has been called if you need the session information at a later point.
  • If the Branch session has already been initialized, the callback will return immediately, otherwise, it will return once Branch has been initialized.

first(callback)

Parameters

ParameterTypeDescriptionRequired
callbackfunctionCallback to read the session data.N

Returns the same session information and any referring data, asBranch.init did when the app was first installed.

  • This is meant to be called after Branch.init has been called if you need the first session information at a later point.
  • If the Branch session has already been initialized, the callback will return immediately, otherwise, it will return once Branch has been initialized.

identify(identity) (Deprecated)

Sets the identity of a user and returns the data. To use this function, pass a unique string that identifies the user - this could be a unique user ID, UUID, Facebook ID, etc.

setIdentity(identity, callback)

🚧

Sending PII

Be sure to not send any PII through this method. For additional details, please view our guide on Best Practices to Avoid Sending PII to Branch

Parameters

ParameterTypeDescriptionRequired
identitystringA string uniquely identifying the user - often a user ID.Y
callbackfunctionCallback that returns the user's Branch identity id and unique link.N

Usage

branch.setIdentity(
    identity,
    callback (err, data)
);

Callback Format

callback(
     "Error message",
     {
          randomized_bundle_token:             '12345', // Server-generated ID of the user identity, stored in `sessionStorage`.
          link:                    'url',   // New link to use (replaces old stored link), stored in `sessionStorage`.
          referring_data_parsed:    { },      // Returns the initial referring data for this identity, if exists, as a parsed object.
          referring_identity:      '12345'  // Returns the initial referring identity for this identity, if exists.
     }
);

logout(callback)

Parameters

ParameterTypeDescriptionRequired
callbackfunctionLogs out the current session, replaces session IDs and identity IDs.N

Usage

branch.logout(
    callback (err)
);

Callback Format

callback(
     "Error message"
);

getBrowserFingerprintId(callback)

Parameters

ParameterTypeDescription
callbackfunctioncallback to read a user's browser-fingerprint-id

Returns the current user's browser-fingerprint-id. If tracking is disabled then 'null' is returned.

Usage

branch.getBrowserFingerprintId(function(err, data) { console.log(data); });

Callback Format

callback(
     null,
     '79336952217731267', // browser-fingerprint-id, stored in `localStorage`.
);

lastAttributedTouchData(attribution_window, callback)

Parameters

ParameterTypeDescriptionRequired
attribution_windownumberThe number of days to look up attribution data for
callbackfunctionCallback to read last attributed touch dataN

Returns last attributed touch data for current user. Last attributed touch data has the information associated with that user's last viewed impression or clicked link.

Usage

branch.lastAttributedTouchData(
    attribution_window,
    callback (err, data)
);

logEvent(event, event_data_and_custom_data, content_items, customer_event_alias, callback)

Parameters

ParameterDescriptionRequired
eventStringY
event_data_and_custom_dataObjectN
content_itemsArrayN
customer_event_aliasStringN
callbackfunctionN

Register commerce events, content events, user lifecycle events and custom events via logEvent()

📘

Note

If this is the first time you are integrating our new event tracking feature via logEvent(), please use the latest Branch WebSDK snippet from the Installation section. This has been updated in v2.30.0 of our SDK.

The guides below provide information about what keys can be sent when triggering these event types:

Usage for Commerce, Content & User Lifecycle "Standard Events"

branch.logEvent(
    event,
    event_data_and_custom_data,
    content_items,
    customer_event_alias,
    callback (err)
);

Usage for "Custom Events"

branch.logEvent(
    event,
    custom_data,
    callback (err)
);

📘

Notes

  • logEvent() sends user_data automatically
  • When firing Standard Events, send custom and event data as part of the same object
  • Custom Events do not contain content items and event data

Example -- How to log a Commerce Event

var event_and_custom_data = {
   "transaction_id": "tras_Id_1232343434",
   "currency": "USD",
   "revenue": 180.2,
   "shipping": 10.5,
   "tax": 13.5,
   "coupon": "promo-1234",
   "affiliation": "high_fi",
   "description": "Preferred purchase",
   "purchase_loc": "Palo Alto",
   "store_pickup": "unavailable"
};

var content_items = [
{
   "$content_schema": "COMMERCE_PRODUCT",
   "$og_title": "Nike Shoe",
   "$og_description": "Start loving your steps",
   "$og_image_url": "http://example.com/img1.jpg",
   "$canonical_identifier": "nike/1234",
   "$publicly_indexable": false,
   "$price": 101.2,
   "$locally_indexable": true,
   "$quantity": 1,
   "$sku": "1101123445",
   "$product_name": "Runner",
   "$product_brand": "Nike",
   "$product_category": "Sporting Goods",
   "$product_variant": "XL",
   "$rating_average": 4.2,
   "$rating_count": 5,
   "$rating_max": 2.2,
   "$creation_timestamp": 1499892855,
   "$exp_date": 1499892854,
   "$keywords": [ "sneakers", "shoes" ],
   "$address_street": "230 South LaSalle Street",
   "$address_city": "Chicago",
   "$address_region": "IL",
   "$address_country": "US",
   "$address_postal_code": "60604",
   "$latitude": 12.07,
   "$longitude": -97.5,
   "$image_captions": [ "my_img_caption1", "my_img_caption_2" ],
   "$condition": "NEW",
   "$custom_fields": {"foo1":"bar1","foo2":"bar2"}
},
{
   "$og_title": "Nike Woolen Sox",
   "$canonical_identifier": "nike/5324",
   "$og_description": "Fine combed woolen sox for those who love your foot",
   "$publicly_indexable": false,
   "$price": 80.2,
   "$locally_indexable": true,
   "$quantity": 5,
   "$sku": "110112467",
   "$product_name": "Woolen Sox",
   "$product_brand": "Nike",
   "$product_category": "Apparel & Accessories",
   "$product_variant": "Xl",
   "$rating_average": 3.3,
   "$rating_count": 5,
   "$rating_max": 2.8,
   "$creation_timestamp": 1499892855
}];

var customer_event_alias = "event alias";

branch.logEvent(
   "PURCHASE",
   event_and_custom_data,
   content_items,
   customer_event_alias,
   function(err) { console.log(err); }
);

createLink(data) (Deprecated)

Creates and returns a deep linking URL. The data parameter can include an object with optional data you would like to store, including Facebook Open Graph data.

data The dictionary to embed with the link. Accessed as session or install parameters from
the SDK.

link(data, callback)

Parameters

ParameterTypeDescriptionRequired
dataObjectLink data and metadata.Y
callbackfunctionReturns a string of the Branch deep
linking URL.
Y

📘

Note

You can customize the Facebook OG tags of each URL if you want to dynamically share content by
using the following optional keys in the data dictionary. Please use thisFacebook tool to debug your OG tags!

KeyValue
"$og_title"The title you'd like to appear for the link in social media
"$og_description"The description you'd like to appear for the link in social media
"$og_image_url"The URL for the image you'd like to appear for the link in social media
"$og_video"The URL for the video
"$og_url"The URL you'd like to appear
"$og_redirect"If you want to bypass our OG tags and use your own, use this key with the URL that contains your site's metadata.

Also, you can set custom redirection by inserting the following optional keys in the dictionary:

KeyValue
"$desktop_url"Where to send the user on a desktop or laptop. By default it is the Branch-hosted text-me service
"$android_url"The replacement URL for the Play Store to send the user if they don't have the app. Only necessary if you want a mobile web splash
"$ios_url"The replacement URL for the App Store to send the user if they don't have the app. Only necessary if you want a mobile web splash
"$ipad_url"Same as above but for iPad Store
"$fire_url"Same as above but for Amazon Fire Store
"$blackberry_url"Same as above but for Blackberry Store
"$windows_phone_url"Same as above but for Windows Store
"$after_click_url"When a user returns to the browser after going to the app, take them to this URL. iOS only; Android coming soon
"$afterclick_desktop_url"When a user on desktop returns to the desktop browser after going to the desktop app, take them to this URL.

You have the ability to control the direct deep linking of each link as well:

KeyValue
"$deeplink_path"The value of the deep link path that you'd like us to append to your URI. For example, you could specify "$deeplink_path": "radio/station/456" and we'll open the app with the URI "yourapp://radio/station/456?link_click_id=branch-identifier". This is primarily for supporting legacy deep linking infrastructure.
"$always_deeplink"true or false. (default is not to deep link first) This key can be specified to have our linking service force try to open the app, even if we're not sure the user has the app installed. If the app is not installed, we fall back to the respective app store or $platform_url key. By default, we only open the app if we've seen a user initiate a session in your app from a Branch link (has been cookied and deep linked by Branch).

Usage

branch.link(
    data,
    callback (err, link)
);

Example

branch.link({
    tags: [ 'tag1', 'tag2' ],
    channel: 'facebook',
    feature: 'dashboard',
    stage: 'new user',
    data: {
        mydata: 'something',
        foo: 'bar',
        '$desktop_url': 'http://myappwebsite.com',
        '$ios_url': 'http://myappwebsite.com/ios',
        '$ipad_url': 'http://myappwebsite.com/ipad',
        '$android_url': 'http://myappwebsite.com/android',
        '$og_app_id': '12345',
        '$og_title': 'My App',
        '$og_description': 'My app\'s description.',
        '$og_image_url': 'http://myappwebsite.com/image.png'
    }
}, function(err, link) {
    console.log(err, link);
});

Callback Format

callback(
    "Error message",
    'https://bnc.lt/l/3HZMytU-BW' // Branch deep linking URL
);

deepview(data, options, callback)

Parameters

ParameterTypeDescriptionRequired
dataObjectObject of all link data, same as branch.link().Y
optionsObject{make_new_link: whether to create a new link even if one already exists. open_app, whether to try to open the app passively (as opposed to opening it upon user clicking); defaults to true}.N
callbackfunctionReturns an error if the API call is unsuccessful.N

Turns the current page into a "deepview" – a preview of app content. This gives the page two
special behaviors:

  1. When the page is viewed on a mobile browser, if the user has the app installed on their phone, we will try to open the app automaticaly and deeplink them to this content (this can be toggled off by turning open_app to false, but this is not recommended).
  2. Provides a callback to open the app directly, accessible as branch.deepviewCta();
    you'll want to have a button on your web page that says something like "View in app", which calls this function.

See this tutorial for a full guide on how to use the deepview functionality of the Web SDK.

Usage

branch.deepview(
    data,
    options,
    callback (err)
);

Example

branch.deepview(
    {
        channel: 'facebook',
        data: {
            mydata: 'content of my data',
            foo: 'bar',
            '$deeplink_path': 'item_id=12345'
        },
        feature: 'dashboard',
        stage: 'new user',
        tags: [ 'tag1', 'tag2' ],
    },
    {
        make_new_link: true,
        open_app: true
    },
    function(err) {
        console.log(err || 'no error');
    }
);

Callback Format

callback(
    "Error message"
);

deepviewCta()

Perform the branch deepview CTA (call to action) on mobile after branch.deepview() call is finished.

If the branch.deepview() call is finished with no error, when branch.deepviewCta() is called, an attempt is made to open the app and deeplink the end user into it; if the end user does not have the app installed, they will be redirected to the platform-appropriate app stores. If on the other hand, branch.deepview() returns with an error, branch.deepviewCta() will fall back to redirect the user using Branch dynamic links.

If branch.deepview() has not been called, an error will arise with a reminder to call branch.deepview() first.

Usage

$('a.deepview-cta').click(branch.deepviewCta); // If you are using jQuery

document.getElementById('my-elem').onClick = branch.deepviewCta; // Or generally

<a href='...' onclick='branch.deepviewCta()'> // In HTML

// We recommend to assign deepviewCta in deepview callback:
branch.deepview(data, option, function(err) {
    if (err) {
        throw err;
    }
    $('a.deepview-cta').click(branch.deepviewCta);
});

// You can call this function any time after branch.deepview() is finished by simply:
branch.deepviewCta();

When debugging, please call branch.deepviewCta() with an error callback like so:

branch.deepviewCta(function(err) {
	if (err) {
		console.log(err);
	}
});

addListener(event, listener)

Parameters

ParameterTypeDescriptionRequired
eventStringSpecify which events you would like to listen for. If not defined, the observer will receive all events.N
listenerfunctionListening function that receives an event as a string and optional data as an object.R

The Branch Web SDK includes a simple event listener, that currently only publishes events for Journeys events.

Future development will include the ability to subscribe to events related to all other Web SDK functionality.

Example

var listener = function(event, data) { console.log(event, data); }

// Specify an event to listen for
branch.addListener('willShowJourney', listener);

// Listen for all events
branch.addListener(listener);

Available Journey Events:

  • willShowJourney: Journey is about to be shown.
  • didShowJourney: Journey's entrance animation has completed and it is being shown to the user.
  • willNotShowJourney: Journey will not be shown and no other events will be emitted.
  • didClickJourneyCTA: User clicked on Journey's CTA button.
  • didClickJourneyClose: User clicked on Journey's close (X) button.
  • didClickJourneyContinue: User clicked on the dismiss Journey text.
  • willCloseJourney: Journey close animation has started.
  • didCloseJourney: Journey's close animation has completed and it is no longer visible to the user.
  • didCallJourneyClose: Emitted when developer calls branch.closeJourney() to dismiss Journey.

removeListener(listener)

Parameters

ParameterTypeDescriptionRequired
listenerfunctionReference to the listening function you would like to remove. note: this must be the same reference that was passed to branch.addListener(), not an identical clone of the function.Y

Remove the listener from observations, if it is present. Not that this function must be passed a referrence to the same function that was passed to branch.addListener(), not just an identical clone of the function.

setBranchViewData(data)

Parameters

ParameterTypeDescriptionRequired
dataObjectObject of all link data, same as Branch.link().Y

This function lets you set the deep link data dynamically for a given mobile web Journey. For example, if you desgin a full page interstitial, and want the deep link data to be custom for each page, you'd need to use this function to dynamically set the deep link params on page load. Then, any Journey loaded on that page will inherit these deep link params.

Usage

branch.init(...);
branch.setBranchViewData(
  data // Data for link, same as Branch.link()
);

Example

branch.init(...);
branch.setBranchViewData({
  tags: ['tag1', 'tag2'],
  data: {
    mydata: 'something',
    foo: 'bar',
    '$deeplink_path': 'open/item/1234'
  }
});

closeJourney(callback)

Parameters

ParameterTypeDescriptionRequired
callbackfunctionJourneys include a close button the user can click, but you may want to close the Journey with a timeout, or via some other user interaction with your web app. In this case, closing the Journey is very simple by calling Branch.closeJourney().N

Usage

branch.closeJourney(function(err) { console.log(err); });

disableTracking(disableTracking)

Parameters

ParameterTypeDescriptionRequired
disableTrackingBooleantrue disables tracking and false re-enables tracking.N

📘

Notes

  • disableTracking() without a parameter is a shorthand for disableTracking(true).
  • If a call to disableTracking(false) is made, the WebSDK will re-initialize. Additionally, if tracking_disabled: true is passed as an option to init(), it will be removed during the re-initialization process.

Allows User to Remain Private

This will prevent any Branch requests from being sent across the network, except for the case of deep linking.
If someone clicks a Branch link, but has expressed not to be tracked, we will return deep linking data back to the
client but without tracking information.

In do-not-track mode, you will still be able to create links and display Journeys however, they will not have identifiable information associated to them. You can change this behavior at any time, by calling the aforementioned function.

The do-not-track mode state is persistent: it is saved for the user across browser sessions for the web site.

setDMAParamsForEEA

🚧

Warning: false by Default

Please note that the 3 parameters passed to setDMAParamsForEEA() are all false by default.

Failure to include user consent signals may result in attribution or campaign performance degradation. For additional information, please reach out to your Google AM.

MethodDescription
setDMAParamsForEEA(boolean eeaRegion, boolean adPersonalizationConsent, boolean adUserDataUsageConsent)Sets the value of parameters required by Google Conversion APIs for DMA Compliance in the EEA region.

Parameters

ParameterTypeDescriptionRequired
eeaRegionBooleanSet to true if user is included in European Union regulations. For example, if the user is located within the EEA, they are within the scope of DMA.

Set to false if user is considered excluded from European Union regulations.
Required if EU regulations apply to this user
adPersonalizationConsentBooleanSet to true if user has granted consent for ads personalization.

Set to false if user has denied consent for ads personalization.
Required if eeaRegion is set to true (i.e., EU regulations apply to this user)
adUserDataUsageConsentBooleanSet to true if user has granted consent for 3P transmission of user-level data for ads.

Set to false is user has denied consent for 3P transmission of user-level data for ads.
Required if eeaRegion is set to true (i.e., EU regulations apply to this user)

Usage

The setDMAParamsForEEA() method can be called before or after the init() method, and will be queued accordingly:

// Example for an EEA resident who has denied both ad personalization and data usage consent
branch.setDMAParamsForEEA(true,false,false);