Web Advanced Features

Initialize Branch features

branch.init('key_live_OUR_KEY_GOES_HERE', function(err, data) {
console.log(err, data);
var options = { no_journeys: true };
branch.init('key_live_YOUR_KEY_GOES_HERE', options, function(err, data) {
  console.log(err, data);
});
  • Returns the following inside the data object
KeyValue
data_parsedobject. If the user was referred from a link, and the link has associated data, the data is passed in here.
has_appboolean. Does the user have the app installed already, using Branch's persona data.
identityoptional - string.Unique string that identifies the user, if set from setIdentity
referring_linkstring. The referring link clicked, if available.
referring_identitystring. If the user was referred from a link, and the link was created by a user with an identity, that identity is here.

Create Deep Link

var linkData = {
  campaign: 'content 123',
  channel: 'facebook',
  feature: 'dashboard',
  stage: 'new user',
  tags: [ 'tag1', 'tag2', 'tag3' ],
  alias: '',
  data: {
    'custom_bool': true,
    'custom_int': Date.now(),
    'custom_string': 'hello',
    '$og_title': 'Title',
    '$og_description': 'Description',
    '$og_image_url':'http://lorempixel.com/400/400'
  }
};

branch.link(linkData, function(err, link) {
  console.log(link);
});

Share Deep Link

  • Will generate a Branch deep link and tag it with the channel the user selects

  • Uses Deep Link Properties

<!-- shareable elements -->
<button id="button">deep link</button>
<a id="anchor" href="#">deep link</a>
var linkData = {
  campaign: 'content 123',
  channel: 'facebook',
  feature: 'dashboard',
  stage: 'new user',
  tags: [ 'tag1', 'tag2', 'tag3' ],
  alias: '',
  data: {
    'custom_bool': true,
    'custom_int': Date.now(),
    'custom_string': 'hello',
    '$og_title': 'Title',
    '$og_description': 'Description',
    '$og_image_url':'http://lorempixel.com/400/400'
  }
};

branch.link(linkData, function(err, link) {
  // bind elements
  document.getElementById('button').onclick = function() {
    window.open(link || err);
  };
  document.getElementById('anchor').href = link || err;
});

Read Deep Link

  • Retrieve Branch data from a deep link

  • Best practice to receive data from the listener (to prevent a race condition)

  • Validate with Testing read deep link

  • Listener

branch.init('key_live_YOUR_KEY_GOES_HERE', function(err, data) {
  console.log(err, data);
});
  • Latest data
branch.data(function(err, data) {
  console.log(err, data);
});
  • First data
branch.first(function(err, data) {
  console.log(err, data);
});

Create Journeys Banner

  • Converts mobile users to app users

  • Create a Journey on the Branch Dashboard

  • Validate by testing your website on a mobile device

  • Append additional deep link data to the Journey button

// optional additional deep link data
var linkData = {
  campaign: 'content 123',
  channel: 'facebook',
  feature: 'dashboard',
  stage: 'new user',
  tags: [ 'tag1', 'tag2', 'tag3' ],
  alias: '',
  data: {
    'custom_bool': true,
    'custom_int': Date.now(),
    'custom_string': 'hello',
    '$og_title': 'Title',
    '$og_description': 'Description',
    '$og_image_url':'http://lorempixel.com/400/400'
  }
};

branch.setBranchViewData(linkData);
// close
branch.closeJourney(function(err, data) {
  console.log(err, data);
});

// reopen
branch.track("pageview");

Create Text Message

  • Converts desktop users to app users

  • Sends a SMS text message with a deep link to a phone number

<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
    <script type="text/javascript">
        (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 banner closeBanner creditHistory credits data deepview deepviewCta first getCode init link logout redeem referrals removeListener sendSMS setBranchViewData setIdentity track validateCode".split(" "), 0);

        branch.init('YOUR-BRANCH-KEY');
            function sendSMS(form) {
                var phone = form.phone.value;
                var linkData = {
                    tags: [],
                    channel: 'Website',
                    feature: 'TextMeTheApp',
                    data: {
                        'foo': 'bar'
                    }
                };
                var options = {};
                var callback = function(err, result) {
                    if (err) {
                        alert("Sorry, something went wrong.");
                    }
                    else {
                        alert("SMS sent!");
                    }
                };
                branch.sendSMS(phone, linkData, options, callback);
                form.phone.value = "";
            }
    </script>
</head>
<body>
        Send SMS
        <form onsubmit="sendSMS(this); return false;">
            <input id="phone" name="phone" type="tel" placeholder="(650) 123-4567" />
            <br/>
            <input type="submit"/>
        </form>
    </body>
</html>

Use a custom form with SendSMS()

If you have an existing form for users to input their phone number, you can put our Text Me The App behind it. Add the following code somewhere inside the <head></head> tags on your website.

<script type="text/javascript">
function sendSMS(form) {
  branch.sendSMS(
    phone: form.phone.text,
    {
      channel: 'Website',
      feature: 'Text-Me-The-App',
      data: {
        foo: 'bar'
      }
    },
    { make_new_link: false }, // Default: false. If set to true, sendSMS will generate a new link even if one already exists.
    function(err) { console.log(err); }
  );
}
</script>

Host Deep Link Data

  • Make it easier for marketers to create deep links

  • Used for Journeys, Universal Emails, Quick links, and the Chrome Extension

  • Branch will scrape the web URL for deep link data on link creation

  • If you host deep link data in your website source code, Branch can automatically convert a simple web URL into a corresponding Branch link that deep links to relevant content in your mobile app.

  • Branch will also parse your Content Analytics data and provide you with more valuable information about which content is driving clicks, installs, opens, and in-app engagement.

  • The first step to successfully putting deep link data on your website is to understand how your deep links correspond to your web URLs. Ask yourself the following questions, and group your content accordingly.

      - Do you have any content on web that doesn’t exist in the app? Examples include: time-sensitive promotions, splash pages, micro-sites.
    
      - For content that has corresponding app content, what type of pages do you have? Examples include: search result pages, category homepages, product pages.
    
      - If you’ve already set up deep linking (if you haven’t set up deep linking skip this step): what does your deep linking schema look like? Do you use different keys for different content? Do you have required key/value pairs that aren’t content specific? Examples include: `productPage` or `categoryPage` keys, or `product_view=true`.
    
  • Validate by creating a Quick Link and fill in web URL to your web page

Example URLURL dataMetatags to add to your site
https://shop.com/shoes/brown-loafersproductId=1234, productView=true<meta name="branch:deeplink:productId" content="1234" />, <meta name="branch:deeplink:productView" content="true" />
https://shop.com/shoescategoryId=5678<meta name="branch:deeplink:categoryId" content="5678" />
https://shop.com/a-great-movieNo corresponding app content (open web)<meta name="branch:deeplink:$web_only" content="true" />

Troubleshooting

  • If you have Facebook App Links metatags on your site and working with your app, then you can skip these instructions. Branch will automatically fetch App Links tags and add them to your deep link data.
  • Do not use Google Tag Manager (GTM) to insert your content metatags. GTM requires JavaScript to load on the page, and the Branch link data scraper does not support JavaScript execution.
  • If you need to whitelist the postback server IP addresses for security purposes, they are listed here.

Track Users

  • Sets the identity of a user (email, ID, UUID, etc) for events, deep links, and referrals

  • Validate with the Branch Dashboard

branch.setIdentity('123456');
branch.setIdentity('123456', function (err, data) {
  console.log(err, data);
});
  • Removes the identity of a user
branch.logout();
branch.logout(function(err, data) {
console.log(err, data);
});

Track Events

For a complete list of all standard events the Branch SDK tracks, please see Tracking Commerce, Content, Lifecycle and Custom Events.

Commerce Event

  • Registers a custom commerce event

  • Validate with the Branch Dashboard

  • If you track commerce events without a currency, we assume they are USD. If you track commerce events with a currency other than USD, we will convert the revenue specified to USD, using a recent exchange rate.

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": 1499892854966,
   "$exp_date": 1499892854966,
   "$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": 1499892854966
}];

var customer_event_alias = "my custom alias";

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

Content Event

Content events are events that occur when a user engages with your in-app content. For example, if you have in-app articles, you would want to track events related to when users search, view content, rate the content, and share. This can apply to a wide variety of in-app content, such as blog posts, music, video, pictures, and e-commerce catalogue items.

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": 1499892854966,
   "$exp_date": 1499892854966,
   "$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": 1499892854966
}];

var customer_event_alias = "my custom alias";

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

Custom Event

  • Registers a custom event

  • Events named open, close, install, and referred session are Branch restricted

  • Best to Track users before Track events to associate a custom event to a user

  • Validate with the Branch Dashboard

❗️

Custom Event Name

The name custom event is reserved by Branch. Please ensure you give your custom event an actual name.

We strongly recommend using custom event names that contain no more than 40 characters, contain only letters, numbers, hyphens, spaces and underscores, and do not start with a hyphen.

var custom_data = {
   "Custom_Event_Property_Key1": "Custom_Event_Property_val1",
   "Custom_Event_Property_Key2": "Custom_Event_Property_val2"
};

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

Lifecycle Event

Lifecycle events can be described as events a user takes in your app to continue progressing. These events can apply to game apps, as well as non game apps, for when a user completes a user profile, registration or tutorial.

var event_and_custom_data = {
   "transaction_id": "tras_Id_1234",
   "description": "Preferred purchase",
   "registration_id": "12345"
};

var customer_event_alias = "my custom alias";

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

Handle Listeners

  • Subscribe and unsubscribe to Branch events
// all Branch events
branch.addListener(listener);
branch.addListener('willShowJourney', listener);
branch.removeListener(listener);
KeyUsage
willShowJourneyJourney is about to be shown.
didShowJourneyJourney's entrance animation has completed and it is being shown to the user.
willNotShowJourneyJourney will not be shown and no other events will be emitted.
didClickJourneyCTAUser clicked on Journey's CTA button.
didClickJourneyCloseUser clicked on Journey's close button.
willCloseJourneyJourney close animation has started.
didCloseJourneyJourney's close animation has completed and it is no longer visible to the user.
didCallJourneyCloseEmitted when developer calls branch.closeJourney() to dismiss Journey.

Handle Firebase App Indexing

  • Inserts Firebase App Indexing tags on your website which will help Google index and surface content from your App to Google Search

    • For example:
<link rel="alternate" href="android-app://{androidPackageName}/{androidURL}?{branch_tracking_params_and_additional_deep_link_data}"/>
<link rel="alternate" href="ios-app://{iosAppId}/{iosURL}?{branch_tracking_params_and_additional_deep_link_data}"/>
  • If optional parameters above are not specified, Branch will try to build Firebase App Indexing tags using your page's App Links tags. Alternatively, if optional parameters are specified but Firebase App Indexing tags already exist on your webpage then Branch tracking params will be appended to the end of these tags and ignore what is passed into Branch.autoAppIndex().

  • Analytics related to Google's attempts to index your App's content via this method can be found on your Branch Dashboard where channel is Firebase App Indexing and feature is Auto App Indexing

branch.autoAppIndex({
  iosAppId:'123456789',
  iosURL:'example/home/cupertino/12345',
  androidPackageName:'com.somecompany.app',
  androidURL:'example/home/cupertino/12345',
  data: {
    "walkScore": 65,
    "transitScore": 50
  }
}, function(err, data) {
  console.log(err, data);
});
KeyUsage
"androidPackageName"Android App's package name
"androidURL"A custom scheme for your Android App such as: example/home/cupertino/12345 where example is the App's URI scheme and home/cupertino/12345 routes to unique content in the App
"iosAppId"iTunes App Store ID for your iOS App
"iosURL"A custom scheme for your iOS App such as: example/home/cupertino/12345
"data"Any additional deep link data that you would like to pass to your App

Enable / Disable User Tracking

  • In order to help our customers comply with GDPR and other laws that restrict data collection from certain users, we’ve updated our Web SDK with a Do Not Track mode. This way, if a user indicates that they want to remain private on your website, or if you otherwise determine that a particular user should not be tracked, you can continue to make use of the Branch Web SDK (e.g. for creating Branch links) while not tracking that user. This state is persistent, meaning that it’s saved for the user across browser sessions for the web site. This setting can also be enabled across all users for a particular link, or across your Branch links.

  • To enable Do Not Track Mode during initialization, include the tracking_disabled flag, with a value of true, into the options during initialization:

branch.init( 'BRANCH_KEY',
        {
            ‘tracking_disabled’ : true
        }
);
  • To enable Do Not Track Mode following initialization, call disableTracking(true). If you call disableTracking() with no argument, it will default to disableTracking(true). Use disableTracking(false) to resume tracking.

Updated about a month ago


Recommended Next Steps

Web SDK FAQs

Web Advanced Features


Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.