> For the complete documentation index, see [llms.txt](https://help.branch.io/llms.txt).

# Web SDK Advanced Features

> Implement advanced Branch Web SDK features in JavaScript, with prerequisites and code for each method.

## Overview

The Branch Web SDK exposes a set of methods specifically made for websites, which you can call using JavaScript.

## Before you begin

Before you get started implementing the features on this page, you first need to:

1. Create an account in the [Branch Dashboard](https://help.branch.io/developer-hub/web-basic-integration.md#_1-configure-branch).
2. [Integrate](https://help.branch.io/developer-hub/web-basic-integration.md#_3-initialize-branch) the Branch Web SDK into your web app.
3. [Validate](https://help.branch.io/developer-hub/web-basic-integration.md#_4-validate-integration) your Branch Web SDK integration.

> **Note: Branch data retention policy**
>
> Before sending data to Branch, review the "[Data Branch Hashes](https://help.branch.io/account-hub/best-practices-to-minimize-data-sent-to-branch.md#data-branch-hashes)" section of our data best practices guide for field definitions and retention policies.

## Web SDK fields

The Branch Web SDK provides relevant information about Branch [Links](https://help.branch.io/marketer-hub/category/create-links.md) and [Banners](https://help.branch.io/developer-hub/category/journeys.md) (Journeys) using the following fields:

| Field | Description | Example |
| --- | --- | --- |
| `sdk` | The Branch Web SDK version that was loaded on the webpage. | `sdk=web2.52.5` |
| `link_identifier` | A unique ID generated by Branch for a Branch Link click. This is set when a user is referred to the site from a Branch Link. | `link_identifier="348527481794276288"` |
| `options` | The Branch SDK [initialization options](https://help.branch.io/developer-hub/web-basic-integration.md#example-with-additional-options). | `options={no_journeys:true};` |
| `initial_referrer` | Referral URL that led to the current page where the Branch Web SDK logged web session start.<br>Specified by the client. | `"initial_referrer=https://www.google.com/"` |
| `branch_key` | The Branch Key used to initialize the Branch Web SDK.<br>Available in the [Branch Dashboard](https://dashboard.branch.io/account-settings/profile). | `branch_key=key_live_00000000000` |
| `event` | Name of the Branch Event that initialized the Branch Web SDK.<br>Values can be `web_session_start` or `pageview`. | `event=pageview` |
| `metadata` | Custom metadata sent by you at the time of Branch initialization. | `metadata={ "event_id":"value"}` |
| `no_journeys` | Whether Branch Banners (Journeys) should show on the page where the Branch Web SDK was initialized.<br>Default is `false`. | `no_journeys=true` |
| `feature` | Analytics tag set at the time of Branch Web SDK initialization, if applicable. | `feature=journeys` |
| `data` | Branch Deep Link data, if the end user was redirected from a Branch Deep Link. | `data= {"$canonical_url":"value"}` |
| `title` | The title of the web page where the Branch Web SDK was initialized.<br>This title is hosted as part of the meta tags.<br>Only gets returned if available. | `title="Branch Metrics Web SDK Example App"` |
| `description` | The description of the web page where the Branch Web SDK was initialized. This title is hosted as part of the meta tags. Only gets returned if available. | `description="A basic example of the Branch Web SDK."` |

## General deep linking

Branch Deep Links are encapsulated with Deep Link properties, which get passed to Branch on a user's click.

#### Create deep links

Use the `link()` method to create a Branch Deep Link:

```javascript
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);
});
```

To test your Branch Deep Link configuration, follow our testing [guide](https://help.branch.io/developer-hub/web-testing.md#link-debugger).

#### Share deep links

Generate a Branch Deep Link encapsulated with Deep Link [properties](https://help.branch.io/marketer-hub/deep-link-reference.md#create-deep-links), and tag it with the channel the user selects.

```xml
<!-- shareable elements -->
<button id="button">deep link</button>
<a id="anchor" href="#">deep link</a>
```

```javascript
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

You can read a Branch Deep Link to retrieve data from it. This must happen after Branch initialization.

The best practice is to get the data from the listener, since this will prevent a possible race condition.

```javascript
branch.init('key_live_YOUR_KEY_GOES_HERE', function(err, data) {
  console.log(err, data);
});

// To read latest data, call `data()` method
branch.data(function(err, data) {
  console.log(err, data);
});

// To read first data, call `first()` method
branch.first(function(err, data) {
  console.log(err, data);
});
```

To test reading a Branch Deep Link, follow our testing [guide](https://help.branch.io/developer-hub/web-testing.md#test-reading-deep-link).

## Journeys

#### Access

Access to the Journeys feature requires a premium plan. Please [contact our Sales team](https://www.branch.io/contact-sales/) to learn more about pricing and availability.

#### Journeys Assist

Branch's Journeys Assist feature combines powerful banners and interstitials from Journeys with the measurement capabilities of Ads, Email, and other Branch-powered channels.

This configuration provides you with complete attribution of the user flow.

##### Multi session assists

For multi session assists, set the value of the `enableExtendedJourneysAssist` option to `true` and pass that to the Branch Web SDK during initialization:

```javascript
var options = { 
  enableExtendedJourneysAssist: true, // Enable referring Branch Link expiry for Journeys Assist
  extendedJourneysAssistExpiryTime : 5000 // TTL value in milliseconds for the referring Branch Link
};
branch.init('key_live_YOUR_KEY_GOES_HERE', options, function(err, data) {
  console.log(err, data);
});
```

Note that the value of the `extendedJourneysAssistExpiryTime` option defaults to 7 days.

For more details about Journeys Assist, visit our [guide](https://help.branch.io/marketer-hub/journeys-assist.md).

#### Create Journeys Banner

A Branch Journeys Banner helps you convert mobile web users to app users.

To create a Journeys Banner:

1. Create a new Journey on the [Branch Dashboard](https://dashboard.branch.io/journeys).
2. Validate that the Journey was created successfully by testing your website on a mobile device.
3. Append additional deep link data to the Journey button:

   ```javascript
   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'
     }
   };

   // Set Branch Deep Link data dynamically for a given mobile web Journey
   branch.setBranchViewData(linkData);

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

   branch.track("pageview");
   ```

#### Journeys handle listeners

You can use listeners to subscribe and unsubscribe from event streams related to Journeys.

##### Events

| Event key | Usage |
| --- | --- |
| `willShowJourney` | Journey is about to be shown. |
| `didShowJourney` | Journey entrance animation is complete and is being shown to 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 button. |
| `willCloseJourney` | Journey close animation has started. |
| `didCloseJourney` | Journey close animation is complete and Journey is no longer visible to user. |
| `didCallJourneyClose` | Emitted when developer calls `branch.closeJourney()` to dismiss Journey. |

##### Examples

Subscribe to all events:

```javascript
branch.addListener(listener);
```

Subscribe to a single event, in this case `willShowJourney`:

```javascript
branch.addListener('willShowJourney', listener);
```

Unsubscribe:

```javascript
branch.removeListener(listener);
```

## QR Codes

Branch QR Codes contain a unique Branch Link, which you can use to navigate users to the correct content and for analytics tracking.

To create a Branch QR Code, you'll need to create two JavaScript objects: one for QR Code [settings](https://help.branch.io/apidocs/qr-code/overview.md) and one for QR Code [link params](https://help.branch.io/marketer-hub/deep-link-reference.md#create-deep-links).

Then, call the `qrCode()` method, passing in the two objects you just created, as well as a callback function that returns the actual QR Code.

```javascript
$('#qrCode').click(function() {
	var qrCodeSettings = {
		"code_color":"#000000",
		"background_color": "#FFFFFF",
		"margin": 5,
		"width": 1000,
		"image_format": "png"
	};
	var qrCodeParams = {
		tags: [ 'tag1', 'tag2' ],
		channel: 'sample app',
		feature: 'create link',
		stage: 'created link',
		type: 1,
		data: {
			mydata: 'bar',
			'$desktop_url': 'https://cdn.branch.io/example.html',
			'$og_title': 'Branch Metrics',
			'$og_description': 'Branch Metrics',
			'$og_image_url': 'http://branch.io/img/logo_icon_white.png'
		}
	};
	branch.qrCode(qrCodeParams, qrCodeSettings, function(err, qrCode) {
		response.html('<img src="data:image/png;charset=utf-8;base64,' + qrCode.base64() + '" width="500" height="500">');
	});
});
```

#### Access

Basic Branch QR Codes are included in the free tier of the Branch Growth Platform. For more advanced QR Code capabilities, see our Engagement [product](https://help.branch.io/marketer-hub/products.md).

## Include deep link data in HTML

Hosting data for Branch Links directly in your HTML gives Branch a way to scrape the page for that data and use it when creating a deep link. This makes it easier for marketers to create Branch Links.

This approach can be used for [Journeys](https://help.branch.io/marketer-hub/journeys-overview.md), [Emails](https://help.branch.io/marketer-hub/email-overview.md), [Short Links](https://help.branch.io/marketer-hub/create-web-links.md), and the [Chrome Extension](https://chromewebstore.google.com/detail/branch-link-creator/pekdpppibljpmpbcjelehhnldnfbglgf?pli=1).

#### How it works

- During link creation, provide Branch with a web URL to scrape. Branch will scrape the page for relevant data and include it in the deep link properties.
- If you include link data in your website source code, Branch can automatically convert a simple web URL into a corresponding deep link that takes the user to relevant content in your app.
- Branch will parse your Content Analytics data and provide you with more valuable information about which content is driving clicks, installs, opens, and in-app engagement.

#### Important considerations

Please note that:

- Branch only scrapes web tags when a new link is created.
- When Branch scrapes for this link data, no JavaScript will run on the page. Therefore, you will need to add the tags hosting the data directly to the HTML. This data should not be injected at page load via JavaScript or a tag manager.
- The scraper will handle 30 redirects until it gets a `200` response.
- The maximum number of redirected pages Branch will scrape data from is 8.

#### Implementation

The first step to successfully including link data in your HTML 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:

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

#### Examples

The examples below include the link data Branch should pick up, and the corresponding meta tags that need to be added to the web page for that to happen:

| Example URL | Example URL Data | Corresponding HTML Meta Tags |
| --- | --- | --- |
| <https://shop.com/shoes/brown-loafers> | `productId=1234`, `productView=true` | <br>`<meta name="branch:deeplink:productId" content="1234" />`  `<meta name="branch:deeplink:productView" content="true" />`<br> |
| <https://shop.com/shoes> | `categoryId=5678` | `<meta name="branch:deeplink:categoryId" content="5678" />` |
| <https://shop.com/a-great-movie> | No corresponding app content ([open web](https://help.branch.io/marketer-hub/deep-link-reference.md)). | `<meta name="branch:deeplink:$web_only" content="true" />` |

#### Validate

To validate that you are properly including link data in your HTML:

1. Navigate to the Link Manager in the [Branch Dashboard](https://dashboard.branch.io/quick-links/manager).
2. Click on the **Create** button to start creating a new Branch Short Link.
3. In the "Original Web URL" box, include the URL for your web page.

#### Troubleshoot

If you find that Branch cannot scrape your web pages, you may need to put Branch's IP addresses on your allow list:

- 52.9.159.121/32
- 52.9.176.205/32
- 52.9.188.221/32
- 52.9.188.236/32
- 44.247.175.42/32
- 35.160.5.60/32
- 44.238.95.201/32
- 35.163.128.27/32
- 52.34.127.49/32
- 44.247.58.38/32
- 44.231.103.124/32
- 100.21.145.61/32
- 35.167.148.222/32
- 44.237.121.167/32
- 52.33.75.0/32
- 52.43.119.253/32

## Set custom deep link path

Branch automatically pulls meta tags for your convenience.

If canonical URL is set as a meta tag, it will become `$deeplink_path` in the Branch system by default.

However, you can override this default setting by manually setting `$deeplink_path` to the path your mobile app URL taxonomy uses for deep linking. This is done using the content field of the meta tag:

```javascript
<meta name="branch:deeplink:$deeplink_path" content="recipes/456789" />

branch.init('key_live_YOUR_KEY_GOES_HERE', function(err, data) {
  if (document.querySelectorAll("meta[name='branch:deeplink:$deeplink_path']").length > 0) {
    var meta = document.querySelector("meta[name='branch:deeplink:$deeplink_path']").getAttribute("content");
    branch.setBranchViewData({
      data:{
        '$deeplink_path':meta
      }
    });
  }
});
```

For more information on the `branch:deeplink:` keys you can use to customize your meta tags, please reference [this table](https://help.branch.io/marketer-hub/deep-link-reference.md).

#### Troubleshoot

- If you have [Facebook App Links meta tags](https://developers.facebook.com/docs/applinks) on your site that work with your app, then you can skip the instructions in this section. Branch will automatically fetch App Links tags and add them to your Branch Deep Link data.
- Do not use Google Tag Manager (GTM) to insert your content meta tags. GTM requires JavaScript to load on the page, and the Branch data scraper does not support JavaScript execution.
- If you need to allowlist the postback server IP addresses for security purposes, they are listed [here](https://help.branch.io/marketer-hub/basic-postback-configuration.md#allowlist-postback-ip-addresses).

## Track events

By default, the Branch Web SDK tracks clicks, opens, installs, reinstalls, impressions, and Journeys dismissals automatically (out-of-the-box).

On web, an open is called a `web_session_start`. This event is triggered every time a webpage with the web SDK opens in a new tab, or when a user clicks on a Branch Link and is redirected to a page with the web SDK.

You can also [track special user actions or application-specific events](https://help.branch.io/developer-hub/track-branch-events.md). For example, you can track when a user adds an item to a shopping cart or searches for a keyword.

Learn more about [tracking events](https://help.branch.io/developer-hub/track-branch-events.md) and the `logEvent()` [method](https://help.branch.io/developer-hub/web-full-reference.md#logevent) in our guides.

## User data

#### Google DMA compliance

In response to the European Union's enactment of the Digital Markets Act (DMA), the Branch iOS SDK includes the `setDMAParamsForEEA()` method to help you pass consent information from your user to Google.

The `setDMAParamsForEEA()` method takes 3 parameters:

| Parameter | Type | Description | Required |
| --- | --- | --- | --- |
| `eeaRegion` | `Boolean` | Set 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.<br>Set to `false` if user is considered **excluded** from European Union regulations. | **Required** if EU regulations apply to this user |
| `adPersonalizationConsent` | `Boolean` | Set to `true` if user has **granted** consent for ads personalization.<br>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) |
| `adUserDataUsageConsent` | `Boolean` | Set to `true` if user has **granted** consent for 3P transmission of user-level data for ads.<br>Set to `false` if 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) |

##### Default behavior

When `eeaRegion` is set to `true`, the parameters `adPersonalizationConsent` and `adUserDataUsageConsent` must also be set.

When parameters are successfully set using `setDMAParamsForEEA()`, they will be sent along with every future request to the following Branch endpoints:

- `/v1/install`
- `/v1/open`
- `/v2/event`

> **Warning**
>
> 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.**

##### Usage

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

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

#### Set session identity

A session "identity" is a unique alias attributed to a specific event in the Branch system.

Some scenarios that could leverage the `setIdentity()` function:

- You have your own user IDs that you want to see reflected on conversions in the Branch system.
- You want referral and event data to persist on conversions.

> **Warning**
>
> Do not send any PII through the `setIdentity()` method. For additional details, please view our guide on [Best Practices to Avoid Sending PII to Branch](https://help.branch.io/account-hub/best-practices-to-minimize-data-sent-to-branch.md).

```javascript
// Login and set user identity
branch.setIdentity('123456', function (err, data) {
  console.log(err, data);
});

// Logout
branch.logout(function(err, data) {
	console.log(err, data);
});
```

To confirm that user identities are being set as expected, use the [Liveview](https://dashboard.branch.io/liveview) section of the Branch Dashboard.
