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 editting 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
Chrome | Firefox | Safari | IE |
---|---|---|---|
✔ | ✔ | ✔ | 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".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 :
- be executed in the order that they were called, and
- 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
Parameter | Type | Description | Required |
---|---|---|---|
branch_key | string | Your Branch live key, or (deprecated) your app id. | Y |
options | Object | { } See options table below. | N |
callback | function | Callback 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 asreferring_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, in
sessionStorage
.
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:
Key | Value | Type | Required |
---|---|---|---|
branch_match_id | The 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. | string | N |
branch_view_id | If 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. | string | N |
no_journeys | When true , prevents Journeys from appearing on current page. | boolean | N |
disable_entry_animation | When true , prevents a Journeys entry animation. | boolean | N |
disable_exit_animation | When true , prevents a Journeys exit animation. | boolean | N |
retries | Value specifying the number of times that a Branch API call can be re-attempted. Default 2. | integer | N |
retry_delay | Amount of time in milliseconds to wait before re-attempting a timed-out request to the Branch API. Default 200 ms. | integer | N |
timeout | Duration in milliseconds that the system should wait for a response before considering any Branch API call to have timed out. Default 5000 ms. | integer | N |
metadata | Key-value pairs used to target Journeys users via the "is viewing a page with metadata key" filter. | object | N |
nonce | A nonce value that will be added to branch-journey-cta injected script. Used to allow that script from a Content Security Policy. | string | N |
tracking_disabled | true disables tracking | boolean | N |
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.
data(callback)
Parameters
Parameter | Type | Description | Required |
---|---|---|---|
callback | function | Callback 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
Parameter | Type | Description | Required |
---|---|---|---|
callback | function | Callback 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
Parameter | Type | Description | Required |
---|---|---|---|
identity | string | A string uniquely identifying the user - often a user ID. | Y |
callback | function | Callback 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
Parameter | Type | Description | Required |
---|---|---|---|
callback | function | Logs out the current session, replaces session IDs and identity IDs. | N |
Usage
branch.logout(
callback (err)
);
Callback Format
callback(
"Error message"
);
getBrowserFingerprintId(callback)
Parameters
Parameter | Type | Description |
---|---|---|
callback | function | callback 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
Parameter | Type | Description | Required |
---|---|---|---|
attribution_window | number | The number of days to look up attribution data for | |
callback | function | Callback to read last attributed touch data | N |
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
Parameter | Description | Required | |
---|---|---|---|
event | String | Y | |
event_data_and_custom_data | Object | N | |
content_items | Array | N | |
customer_event_alias | String | N | |
callback | function | N |
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
Parameter | Type | Description | Required |
---|---|---|---|
data | Object | Link data and metadata. | Y |
callback | function | Returns 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!
Key | Value |
---|---|
"$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:
Key | Value |
---|---|
"$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:
Key | Value |
---|---|
"$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
Parameter | Type | Description | Required |
---|---|---|---|
data | Object | Object of all link data, same as branch.link() . | Y |
options | Object | {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 |
callback | function | Returns 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:
- 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).
- 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
Parameter | Type | Description | Required |
---|---|---|---|
event | String | Specify which events you would like to listen for. If not defined, the observer will receive all events. | N |
listener | function | Listening 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:
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
Parameter | Type | Description | Required |
---|---|---|---|
listener | function | Reference 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
Parameter | Type | Description | Required |
---|---|---|---|
data | Object | Object 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
Parameter | Type | Description | Required |
---|---|---|---|
callback | function | Journeys 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
Parameter | Type | Description | Required |
---|---|---|---|
disableTracking | Boolean | true 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 toinit()
, 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.
Updated 4 months ago