Branch Web SDK

repository·main·Indexed 43 days ago

https://github.com/branchmetrics/web-branch-deep-linking-attribution

A JavaScript library for implementing deep linking, Smart Banners, and attribution on web platforms. The SDK enables seamless transitions between web and mobile environments and provides APIs for session management, event tracking, revenue analytics, and user privacy control. Compatible with modern browsers and IE 9-11.

Tokens
1.9K
Snippets
5
Records
10
Agent score
55%

What's inside Branch

  1. Branch Web SDK API Reference Overview

    main

    The Branch Web SDK provides a suite of methods for managing user sessions, tracking events, handling deep linking, and managing user privacy. The API is organized into the following functional areas:

    1. Branch Session

    Manage the user's lifecycle and identity within the SDK.

    • .init(branch_key, options, callback): Initialize the SDK.
    • .data(callback): Retrieve session data.
    • .first(callback): Check if it is the user's first session.
    • .setIdentity(identity, callback): Set user identity.
    • .logout(callback): Log the user out.
    • .crossPlatformIds(callback): Retrieve cross-platform identifiers.
    • .lastAttributedTouchData(attribution_window, callback): Get attribution data.

    2. Event Tracking

    Record user actions and custom events.

    • .track(event, metadata, callback): Track standard events.
    • .logEvent(event, event_data_and_custom_data, content_items, callback): Log specific events with detailed data.

    3. Deep Linking

    Handle incoming links and deep view experiences.

    • .link(data, callback): Create or process links.
    • .deepview(data, options, callback): Trigger a deep view experience.
    • .deepviewCta(): Handle deep view Call to Action.

    4. Event Listener

    Subscribe to SDK events.

    • .addListener(event_listener): Add a listener.
    • .removeListener(listener): Remove a listener.

    5. Journeys Web To App

    Manage the transition from web to mobile applications.

    • .setBranchViewData(data): Set data for the web-to-app journey.
    • .closeJourney(): Close the current journey.

    6. Revenue Analytics

    Track commerce-related data.

    • .trackCommerceEvent(event, commerce_data, metadata, callback): Track revenue and commerce events.

    7. User Privacy

    Control data collection.

    • .disableTracking(disableTracking): Enable or disable tracking.
  2. Important versioning and data escaping notes

    main

    Critical Updates

    • Version < v2.25.0: Users must update to at least v2.25.0 to patch a critical bug related to iOS 11.

    Data Escaping in Journeys

    Depending on your SDK version, the way data is returned in Journeys event handlers varies:

    • WebSDK <= 2.48.0: Journeys link data contains escaped keys and values. Characters ", ', &, <, and > are escaped to their corresponding HTML entities. URLs in both keys and values are URI encoded.
    • WebSDK >= 2.49: Values in Journeys link data are escaped using the same rules as above, but keys are no longer escaped.
  3. Initialize the Branch Web SDK

    main

    To use the SDK, you must call branch.init() with your Branch Key. This is an asynchronous method that accepts a callback function to handle any errors (err) or returned data (data).

    The SDK Command Queue

    While branch.init() is asynchronous, the SDK includes a built-in command queue. This means you do not need to wrap all your SDK calls inside the init callback. As long as branch.init() is called before any other methods, the SDK guarantees that:

    1. All methods are executed in the order they were called.
    2. Each method waits for the previous one to finish before executing.

    Note: If branch.init() fails, all subsequent calls to the Branch SDK will fail.

    Example of calling methods immediately after initialization:

    branch.init('BRANCH_KEY', function(err, data) { /* ... */ });
    branch.banner(...); // This will wait for init to complete
    branch.init('BRANCH KEY', function(err, data) {
        // callback to handle err or data
    });
  4. Install the Branch Web SDK

    main

    The Branch Web SDK is a native JavaScript library that requires no third-party dependencies. It is compatible with all modern browsers that support sessionStorage.

    Browser Support

    • Chrome: Supported
    • Firefox: Supported
    • Safari: Supported
    • IE: 9, 10, 11

    Installation Methods

    Add the following script within your <head> tags. Replace BRANCH KEY with your actual Branch Key from your Branch dashboard.

    <script type="text/javascript">
    	branch.init('BRANCH KEY', function(err, data) {
        	// callback to handle err or data
    	});
    </script>

    2. NPM or Bower

    Install the branch-sdk package via npm or bower.

    3. CommonJS or RequireJS

    For environments like Webpack, Browserify, or RequireJS, you can import the SDK directly:

    CommonJS:

    const branch = require('branch');

    RequireJS/AMD:

    define(['branch'], function(branch) { ... });
    <script type="text/javascript">
    	branch.init('BRANCH KEY', function(err, data) {
        	// callback to handle err or data
    	});
    </script>
  5. Use the command queue for early SDK calls

    main

    To prevent errors when calling Branch methods before the SDK is fully initialized, you can use a command queue. The SDK checks for window['branch']['_q'] during initialization and replays any queued tasks.

    Each task in the queue is an array where the first element is the method name and the subsequent elements are the arguments for that method.

    // Example of queuing a command before the SDK is fully loaded
    window.branch = window.branch || {};
    window.branch._q = window.branch._q || [];
    
    // Queue a call to 'getBranchData' with no arguments
    window.branch._q.push(['getBranchData', []]);
  6. Initialize the Branch SDK instance

    main

    The Branch SDK can be initialized in various JavaScript environments (CommonJS, AMD, or vanilla JS). Once initialized, the main instance is typically exposed via the global branch object in browser environments or via require/import in module environments.

    If commands are issued to the branch object before the SDK has fully loaded, they are placed in a queue (window['branch']['_q']) and automatically re-executed once the branch_instance is ready.

    // In a browser environment, the instance is available on the global window object
    // or via module imports in CommonJS/AMD environments.
    
    // CommonJS usage:
    const branch = require('branch-sdk');
    
    // Vanilla JS / Global usage:
    // window.branch