筛选项

网络完整参考

使用示例 Web 应用

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

要求

该 SDK 需要本地浏览器 Javascript,并且已经在所有具有 sessionStorage 功能的现代浏览器中进行了测试。无需第三方库即可使用 SDK,因为它是100%原生 Javascript。

浏览器特定支持

Chrome

Firefox

Safari

IE

9、10、11

快速安装

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>

您也可以通过 npm 或 bower (branch-sdk) 获取 sdk

Common.JS 和 RequireJS 兼容性

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!

初始化

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.

因此,执行以下操作是100%允许的:

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

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

API 参考

init(branch_key, options, callback)

参数

参数

类型

描述

必要项

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

选项对象中可用的属性:

Key

类型

必要项

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

用途

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

Callback 格式

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.
     }
);

📘

注意

Branch.init 必须在调用任何其他 Branch function 之前被调用。

data(callback)

参数

参数

类型

描述

必要项

callback

function

Callback to read the session data.

N

返回相同的会话信息和任何引用数据,如下所示:Branch.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)

参数

参数

类型

描述

必要项

callback

function

Callback to read the session data.

N

返回相同的会话信息和任何引用数据,如下所示:Branch.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

参数

参数

类型

描述

必要项

身份

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

用途

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

Callback 格式

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)

参数

参数

类型

描述

必要项

callback

function

注销当前会话,替换会话 ID 和身份 ID。

N

用途

branch.logout(
    callback (err)
);

Callback 格式

callback(
     "Error message"
);

getBrowserFingerprintId(callback)

参数

参数

类型

描述

callback

function

callback to read a user's browser-fingerprint-id

返回当前用户的 browser-fingerprint-id。如果禁用追踪,则返回 “null”。

用途

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

Callback 格式

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

lastAttributedTouchData(attribution_window, callback)

参数

参数

类型

描述

必要项

attribution_window

number

The number of days to look up attribution data for

callback

function

Callback to read last attributed touch data

N

返回当前用户的最后归因触点数据。最后归因触点数据具有与该用户的最近浏览展示或点击链接相关的信息。

用途

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

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

参数

参数

描述

必要项

事件

String

Y

event_data_and_custom_data

Object

N

content_items

Array

N

customer_event_alias

String

N

callback

function

N

通过 logEvent()注册 commerce 事件,content 事件,user lifecycle 事件和自定义事件

📘

注意

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.

以下指南提供有关触发这些事件类型时可以发送哪些 key 的信息:

Commerce,contnent 和用户生命周期“标准事件”的用法

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

“自定义事件”的用法

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

📘

注意事项

  • 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嵌入链接的字典。可从
SDK 作为会话或安装参数访问。

链接(数据,回调)

参数

参数

类型

描述

必要项

数据

Object

Link data and metadata.

Y

callback

function

Returns a string of the Branch deep
linking URL.

Y

📘

注意

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

"$og_title"

您希望在社交媒体上显示链接的标题

"$og_description"

您希望在社交媒体中为链接显示的描述

"$og_image_url"

您希望在社交媒体中显示链接的图片 URL

"$og_video"

影片 URL

"$og_url"

您希望显示的 URL

"$og_redirect"

如果您想绕过我们的 OG 标签并使用自己的 OG 标签,请将此 key 与包含您的网站 metadata的 URL 一起使用。

另外,您可以通过在字典插入以下可选 key 来进行自定义重定向:

Key

"$desktop_url"

在台式机或笔记本电脑上将用户发送到这里。默认情况下,它是 Branch 托管的 text-me 服务

"$android_url"

Play Store 的替代 URL,用于在用户没有该应用的情况下向其发送。仅当您想要移动网站启动时才需要

"$ios_url"

App Store 的替代 URL,用于在用户没有该应用的情况下向其发送。仅在您想要移动网站启动时才需要

"$ipad_url"

与上述相同,但适用于 iPad Store

"$fire_url"

与上述相同,但适用于 Amazon Fire Store

"$blackberry_url"

与上述相同,但适用于 Blackberry Store

"$windows_phone_url"

与上述相同,但适用于 Windows Store

"$after_click_url"

当用户转到应用后返回浏览器时,将其带到该 URL。仅限 iOS; Android 版即将面世

"$afterclick_desktop_url"

当桌面上的用户转到桌面应用后返回桌面浏览器时,将其带到该 URL。

您也可以控制每个链接的直接深度链接:

Key

"$deeplink_path"

您希望我们追加到您的 URI 的深度链接路径的值。例如,您可以指定 "$deeplink_path": "radio/station/456",然后我们将使用 URI "yourapp://radio/station/456?link_click_id=branch-identifier" 打开应用。这主要是为了支持旧版深度链接基础架构。

"$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).

用途

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

例如

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 格式

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

deepview(data, options, callback)

参数

参数

类型

描述

必要项

数据

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

将当前页面变成 “deepview” –应用内容的预览。这为页面提供了两种
特殊行为:

  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.

用途

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

例如

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 格式

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.

用途

$('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)

参数

参数

类型

描述

必要项

事件

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.

例如

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。
  • didShowJourney:Journey 的 entrance animation 已完成,并且正在向用户显示。
  • willNotShowJourney:不会显示 Journey,也不会发出其他事件。
  • didClickJourneyCTA:用户点击了 Journey 的 CTA 按钮。
  • didClickJourneyClose:用户点击了 Journey (站到端引流) 的关闭 (X) 按钮。
  • didClickJourneyContinue:用户点击了解除 Journey 文本。
  • willCloseJourney:Journey 的 close animation 已开始。
  • didCloseJourney:Journey 的 close animation 已完成,用户不再可见。
  • didCallJourneyClose: Emitted when developer calls branch.closeJourney() to dismiss Journey.

removeListener(listener)

参数

参数

类型

描述

必要项

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)

参数

参数

类型

描述

必要项

数据

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.

用途

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

例如

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

closeJourney(callback)

参数

参数

类型

描述

必要项

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

用途

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

disableTracking(disableTracking)

参数

参数

类型

描述

必要项

disableTracking

Boolean

true disables tracking and false re-enables tracking.

N

📘

注意事项

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

允许用户保持私密

这将防止发送任何 Branch 网络请求(深度链接除外)
。如果有人点击 Branch Link,但又不想被追踪,我们会将深度链接数据返回给
用户,但不会捕获任何追踪信息。

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.

Do-not-track 模式状态是持久的:它在网站的浏览器会话中为用户进行保存。