### Start Development Server
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/README.md
Use this command to start the local development server. Navigate to http://localhost:3000/dev.html in your browser after running.
```sh
node startDev.js
```
--------------------------------
### Setup Branch Integration Tests
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/test/integration-test.template.html
Requires the 'utils' module and configures Mocha for testing. Includes a workaround for browser loading delays of the Branch SDK.
```javascript
goog.require("utils");
mocha.ui('bdd');
mocha.reporter('html');
// INSERT INIT CODE
if (window.mochaPhantomJS) {
mochaPhantomJS.run();
} else {
// This is pretty hack, but on a lot of browsers in SauceLabs, it take a bit for the branch src to load into the browser. If the tests start before it is loaded, they fail - specifically when Sinon trys to wrap branch._server.
// Note, this is *different* from branch.init, that is called in the tests themselves.
var checkBranchLoadTimer = setTimeout(function() {
if (branch && branch._server) {
onload();
clearTimeout(checkBranchLoadTimer);
}
}, 500);
}
```
--------------------------------
### Branch Web SDK Integration Test Setup
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/test/integration-test.html
This code initializes the Branch SDK and sets up the testing environment using Mocha. It includes a mechanism to ensure the Branch script is loaded before tests run, particularly in environments like SauceLabs.
```javascript
goog.require("utils");
mocha.ui('bdd');
mocha.reporter('html');
(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="SCRIPT_URL_HERE";
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 banner closeBanner closeJourney data deepview deepviewCta first init link logout removeListener setBranchViewData setIdentity track trackCommerceEvent logEvent disableTracking getBrowserFingerprintId crossPlatformIds lastAttributedTouchData setAPIResponseCallback qrCode setRequestMetaData setDMAParamsForEEA setAPIUrl getAPIUrl".split(" "), 0);
if (window.mochaPhantomJS) {
mochaPhantomJS.run();
} else {
// This is pretty hack, but on a lot of browsers in SauceLabs, it take a bit for the branch src to load into the browser.
// If the tests start before it is loaded, they fail - specifically when Sinon trys to wrap branch._server.
// Note, this is *different* from branch.init, that is called in the tests themselves.
var checkBranchLoadTimer = setTimeout(function() {
if (branch && branch._server) {
onload();
clearTimeout(checkBranchLoadTimer);
}
}, 500);
}
```
--------------------------------
### Get Branch Key and API URL
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example.template.html
Retrieves the Branch Key and API URL, with validation for allowed domains. Returns a placeholder if validation fails.
```javascript
function getBranchKey() { const key = "key_live_juoZrlpzQZvBQbwR33GO5hicszlTGnVT"; return key; }
function getApiUrlLocal() { const apiUrl = "https://api.stage.branch.io"; if (!apiUrl.includes("https://*.branch.io")) { console.error('Only https://*.branch.io domains are allowed.'); return "api_place_holder"; } return apiUrl; }
```
--------------------------------
### Trigger Deepview
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example-deepview.html
Calls the `branch.deepview()` method to display a deepview. This example includes custom data and options to open the app.
```javascript
branch.deepview( { 'channel': 'mobile_web', 'feature': 'deepview', data : { '$deeplink_path': 'page/1234', 'user_profile': '7890', 'page_id': '1234', 'custom_data': 1234 } }, { 'open_app': true } );
```
--------------------------------
### Get Branch Script Placeholder
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example.template.html
Returns a placeholder string for the Branch script. This function is a simple placeholder and does not load any actual script.
```javascript
function getBranchScript() { return "script_place_holder" }
```
--------------------------------
### Get Branch Key from Query Parameters
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example.template.html
Retrieves the 'branch_key' from the current URL's query parameters. If not found, it returns a placeholder value.
```javascript
function getBranchKey() {
const queryParams = getQueryParams();
return queryParams['branch_key'] || "key_place_holder"
}
```
--------------------------------
### Get Local API URL from Query Parameters
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example.template.html
Retrieves the 'api_url' from the current URL's query parameters. It also validates the URL using 'isAllowedApiUrl' and alerts the user if it's invalid.
```javascript
function getApiUrlLocal() {
const queryParams = getQueryParams();
const apiUrl = queryParams['api_url'] || "api_place_holder";
if (apiUrl !== "api_place_holder" && !isAllowedApiUrl(apiUrl)) {
alert('Invalid api_url.');
// The original code snippet was truncated here.
// Assuming it might return or handle the error further.
}
// Assuming a return statement would follow if the URL is valid or handled.
// return apiUrl; // Example return if valid
}
```
--------------------------------
### Get Input Value and Sanitize
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example.template.html
Retrieves the value from an input element, adds an error class if empty, and sanitizes the input using DOMPurify. Returns an empty string if the input is empty.
```javascript
function getInputVal(inputID) {
var inputElement = $(inputID);
if (!inputElement.val()) {
inputElement.parent().addClass('has-error');
return '';
} else {
inputElement.parent().removeClass('has-error');
}
return DOMPurify.sanitize(inputElement.val());
}
```
--------------------------------
### Initialize Branch SDK with Callback
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example-deepview.html
Initializes the Branch SDK with a live key and a callback function to update the UI with initialization data or errors.
```javascript
branch.init('key_live_feebgAAhbH9Tv85H5wLQhpdaefiZv5Dv', function(err, data) { document.getElementsByClassName('info')[0].innerHTML = JSON.stringify(data); });
```
--------------------------------
### Initialize UI on Load
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example.template.html
Sets up the initial state of the UI when the page loads by generating configuration buttons and setting label texts.
```javascript
function onLoad() { generateConfigButtons() setLabelText(); } window.onload = onLoad;
```
--------------------------------
### Execute Web SDK Release Script
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/RELEASE_DOCUMENTATION.md
Run the main release script after setting up environment variables and npmjs.org access. Follow the on-screen prompts.
```shell
./release.sh
```
--------------------------------
### Initialize Branch SDK
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/event-example.html
Initializes the Branch SDK with your live key. This should be called once when your application loads.
```javascript
branch.init('key_live_feebgAAhbH9Tv85H5wLQhpdaefiZv5Dv', function(err, data) { });
```
--------------------------------
### Initialize Branch Web SDK
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/docs/1_intro.md
Include this script in your HTML's head tag to initialize the Branch SDK. Replace 'BRANCH KEY' with your actual Branch Key. The callback handles initialization errors or success data.
```html
```
--------------------------------
### Initialize Branch Web SDK
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example.template.html
Initializes the Branch SDK with your Branch key and optional configuration. Ensure the Branch script is loaded before initialization. Handles Branch view data from query parameters.
```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=getBranchScript();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 banner closeBanner closeJourney data deepview deepviewCta first init link logout removeListener setBranchViewData setIdentity track trackCommerceEvent logEvent disableTracking getBrowserFingerprintId crossPlatformIds lastAttributedTouchData setAPIResponseCallback qrCode setRequestMetaData setAPIUrl getAPIUrl setDMAParamsForEEA".split(" "), 0);
var apiUrl = getApiUrlLocal();
branch.setAPIUrl(apiUrl);
branch.setAPIResponseCallback(function(url, method, requestBody, error, status, responseBody) {
console.log('Request: ' + method + ' ' + url + ' body=' + JSON.stringify(requestBody));
if (error) {
console.log('Response: Error ' + error + '; status ' + JSON.stringify(status) + ' body=' + JSON.stringify(responseBody));
} else {
console.log('Response: status ' + JSON.stringify(status) + ' body=' + JSON.stringify(responseBody));
}
});
var initOptions = {};
var metadata = getMetadataFromQp();
if (metadata) {
initOptions.metadata = metadata;
}
const qp = getQueryParams();
if (qp['branchViewData']) {
try {
branchViewData = JSON.parse(qp['branchViewData']);
branch.setBranchViewData(branchViewData);
} catch (e) {
console.error('Failed to parse branchViewData from query params:', e);
}
}
branch.init(getBranchKey(), initOptions, function(err, data) {
$('#session-info').text(JSON.stringify(data, null, 2));
if (err) {
let alertMessage = err.message;
if (getApiUrlLocal().includes('stage')) {
alertMessage += ". Are you connected to VPN?";
}
alert(alertMessage);
}
});
```
--------------------------------
### Initialize Branch SDK
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example-deepview.html
Initializes the Branch SDK with a live key. This should be called early in your application's lifecycle. The callback function handles initialization errors or returns data upon success.
```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="dist/build.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 getBrowserFingerprintId crossPlatformIds lastAttributedTouchData setAPIResponseCallback".split(" "), 0);
```
--------------------------------
### Sequential Branch SDK Method Calls
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/docs/1_intro.md
Demonstrates how to call Branch SDK methods sequentially. The SDK queues method calls, ensuring they execute in order and wait for the previous method to complete. Initialization must occur before any other methods.
```javascript
branch.init(...);
branch.banner(...);
```
--------------------------------
### Handle Init Button Click
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example-deepview.html
Attaches a click event listener to an 'init' button. When clicked, it logs the action and calls `branch.init()` again, updating the response area with the result.
```javascript
$('#init').click(function() { request.html('branch.init();'); // Note that this example is using the key in two places, here and above branch.init('key_live_feebgAAhbH9Tv85H5wLQhpdaefiZv5Dv', function(err, data) { response.html(err || JSON.stringify(data)); }); });
```
--------------------------------
### Initialize Branch SDK
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/event-v2-example.html
Initializes the Branch SDK with a Branch key. Ensure the Branch key is correctly set in the meta tag. This function is typically called on application load.
```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="dist/build.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 getBrowserFingerprintId crossPlatformIds lastAttributedTouchData setAPIResponseCallback".split(" "), 0);
var branch_key = $('meta[name="branch_key"]').attr('content');
console.log('Initializing with branch_key=' + JSON.stringify(branch_key));
$('#request').text('branch.init(' + JSON.stringify(branch_key) + ', function(err, data) {...})');
branch.init(branch_key, function(err, data) {
// using jQuery .text() here avoids XSS in case this is ever hosted.
if (err) {
$('#info').text(JSON.stringify(err));
$('#response').text(JSON.stringify(err));
return;
}
$('#info').text(JSON.stringify(data));
$('#response').text(JSON.stringify(data));
$('.btn').removeAttr('disabled');
});
```
--------------------------------
### Branch SDK Initialization Boilerplate
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/event-example.html
This is a standard boilerplate for initializing the Branch SDK. It ensures the SDK is loaded and ready before use.
```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="dist/build.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 setIdentity track validateCode".split(" "), 0);
```
--------------------------------
### Configure Mocha for Branch Tests
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/test/journeys.html
Sets up the Mocha testing framework with an HTML reporter and requires necessary utility modules for Branch SDK testing. Ensure all required modules are available before running tests.
```javascript
mocha.ui('bdd');
mocha.reporter('html');
goog.require('utils');
goog.require('Server');
goog.require('Branch');
goog.require('resources');
goog.require('storage');
goog.require('session');
if (window.mochaPhantomJS) {
mochaPhantomJS.run();
} else {
onload();
}
```
--------------------------------
### Display Branch Banner
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/event-example.html
Displays a Branch banner to the user. Configure various aspects like icons, text, and behavior. The `sampleParams` object can contain link data.
```javascript
branch.banner( {
icon: 'http://icons.iconarchive.com/icons/wineass/ios7-redesign/512/Appstore-icon.png',
title: 'Demo App',
description: 'Branch Demo app!',
openAppButtonText: 'Open',
downloadAppButtonText: 'Download',
reviewCount: 1000, // Review count
rating: 5, // Average rating from 0 to 5 in increments of .5
iframe: true, // Show banner in an iframe if CSS on your page is conflicting
showMobile: true, // true by default, just set here for an example
showDesktop: true, // true by default, just set here for an example
disableHide: false, // false by default, just set here for an example
forgetHide: true // false by default, just set here for an example
}, // Banner Options
sampleParams // Link data or string of link
);
```
--------------------------------
### Require Branch SDK Modules
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/test/test.html
Loads necessary modules for the Branch SDK tests, including utilities, server components, and core Branch functionality. Ensure these are available in your environment.
```javascript
goog.require('utils');
goog.require('Server');
goog.require('Branch');
goog.require('resources');
goog.require('storage');
goog.require('session');
```
--------------------------------
### Generate Configuration Buttons
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example.template.html
Dynamically creates and appends buttons to the DOM for each API configuration. Clicking a button updates query parameters with the selected configuration.
```javascript
function generateConfigButtons() { const configButtonsContainer = document.getElementById('configButtons'); Object.keys(apiConfigurations).forEach(key => { const config = apiConfigurations[key]; const button = document.createElement('button'); button.classList.add('btn', 'btn-info'); button.textContent = `${config.name}`; button.onclick = () => { updateQueryParams(config.branchKey, config.apiUrl); }; configButtonsContainer.appendChild(button); }); }
```
--------------------------------
### Configure Mocha Test Runner
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/test/test.html
Sets up the Mocha test runner with the 'bdd' interface and 'html' reporter. This configuration is necessary for running the tests.
```javascript
mocha.ui('bdd');
mocha.reporter('html');
```
--------------------------------
### API Configuration Objects
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example.template.html
Defines configuration objects for different Branch API environments (Staging, Production, with and without AC). Each object contains name, branchKey, apiUrl, and appId.
```javascript
const STAGING = "Staging"
const PRODUCTION = "Production"
const STAGING_AC = "Staging AC"
const PRODUCTION_AC = "Production AC"
const apiConfigurations = { STAGING_AC: { name: STAGING_AC, branchKey: "key_live_juoZrlpzQZvBQbwR33GO5hicszlTGnVT", apiUrl: "https://protected-api.stage.branch.io", appId: "1387589751543976586", }, STAGING: { name: STAGING, branchKey: "key_live_plqOidX7fW71Gzt0LdCThkemDEjCbTgx", apiUrl: "https://api.stage.branch.io", appId: "436637608899006753", }, PRODUCTION_AC: { name: PRODUCTION_AC, branchKey: "key_live_hshD4wiPK2sSxfkZqkH30ggmyBfmGmD7", apiUrl: "https://protected-api.branch.io", appId: "1284289243903971463", }, PRODUCTION: { name: PRODUCTION, branchKey: "key_live_iDiV7ZewvDm9GIYxUnwdFdmmvrc9m3Aw", apiUrl: "https://api3.branch.io", appId: "1364964166783226677", }, };
```
--------------------------------
### AWS Access Keys Configuration
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/RELEASE_DOCUMENTATION.md
A sample shell script to store AWS access keys. Ensure this file is added to .gitignore to prevent accidental commits.
```shell
aws_access_keys.sh
```
--------------------------------
### Generate a QR Code for Deep Linking
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example.template.html
Generates a QR code that encodes a deep link. This is useful for sharing links via physical media or other non-click environments.
```javascript
const qrCodeSettings = {
"code_color":"#000000",
"background_color": "#FFFFFF",
"margin": 5,
"width": 1000,
"image_format": "png",
"center_logo_url": "https://branch-assets-usw2.s3.us-west-2.amazonaws.com/branch-badge-dark.svg",
};
const req = { ...linkData,
'qr_code_settings': qrCodeSettings,
}
request.html(`branch.qrCode('${JSON.stringify(req)}');
`);
branch.qrCode(linkData, qrCodeSettings, function(err, qrCode) {
response.html('
');
});
```
--------------------------------
### Fetch First Attributed Touch Data
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example.template.html
Calls the `branch.first()` method to retrieve the first attributed touch data. Displays the request in the '#request' element and the response (or error) in the '#response' element.
```javascript
function callFirst() {
request.html('branch.first();');
branch.first(function(err, data) {
response.html(err || JSON.stringify(data));
});
}
```
--------------------------------
### Enable Tracking
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example.template.html
Enables tracking for the Branch SDK after it has been disabled. Use this to resume tracking user activity.
```javascript
request.text('branch.disableTracking(false);');
branch.disableTracking(false, function() {
response.text('none');
});
```
--------------------------------
### Branch Session Management API
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/docs/web/2_table_of_contents.md
APIs for initializing the Branch SDK, retrieving session data, and managing user identity.
```APIDOC
## Branch Session Management
### .init(branch_key, options, callback)
Initializes the Branch SDK with your unique branch_key.
### .data(callback)
Retrieves the Branch analytics data for the current session.
### .first(callback)
Retrieves the first Branch analytics data for the user.
### .setIdentity(identity, callback)
Sets the identity for the current user.
### .logout(callback)
Logs out the current user.
### .crossPlatformIds(callback)
Retrieves cross-platform identifiers for the user.
### .lastAttributedTouchData(attribution_window, callback)
Retrieves the last attributed touch data within a specified attribution window.
```
--------------------------------
### Log Standard 'VIEW_ITEM' Event
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/event-v2-example.html
Logs a standard 'VIEW_ITEM' event with associated content items and an optional customer event alias. This is used to track when a user views a specific item.
```javascript
var contentItems = [{ "$og_title": "Content Item", "$og_description": "Content description" }];
var customerEventAlias = $('#customer-event-alias').val();
if (customerEventAlias.length == 0) customerEventAlias = null;
var requestText = "branch.logEvent('VIEW_ITEM', null, " + JSON.stringify(contentItems) + ", " + JSON.stringify(customerEventAlias) + ")";
$('#request').text(requestText);
$('#response').text('Waiting for response...');
branch.logEvent( 'VIEW_ITEM', null, contentItems, customerEventAlias, function(err) {
$('#response').text(JSON.stringify(err));
} );
```
--------------------------------
### Track Events with Branch
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/event-example.html
Tracks user events with Branch. This can be used for custom events or predefined actions. Ensure the event name is a string.
```javascript
branch.track('cyan',{'metadata foo': 'metadata bar'},function(err) {});
```
```javascript
branch.track('magenta',{'metadata foo': 'metadata bar'},function(err) {});
```
```javascript
branch.track('yellow',{'metadata foo': 'metadata bar'},function(err) {});
```
```javascript
branch.track('black',{'metadata foo': 'metadata bar'},function(err) {});
```
```javascript
branch.track('red',{'metadata foo': 'metadata bar'},function(err) {});
```
```javascript
branch.track('green',{'metadata foo': 'metadata bar'},function(err) {});
```
```javascript
branch.track('blue',{'metadata foo': 'metadata bar'},function(err) {});
```
```javascript
branch.track('white',{'metadata foo': 'metadata bar'},function(err) {});
```
```javascript
var eventName = String($('#edit-1c').val());
if(typeof eventName.trim === 'function') {
eventName = eventName.trim();
}
if (eventName.length > 0) {
branch.track(eventName,{'metadata foo': 'metadata bar'},function(err) {});
} else {
alert('Enter an alert in the box to fire it off');
}
```
--------------------------------
### Run Mocha Tests with PhantomJS or Onload
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/test/test.html
Executes the Mocha tests. If running in a PhantomJS environment, it uses mochaPhantomJS.run(); otherwise, it calls onload().
```javascript
if (window.mochaPhantomJS) {
mochaPhantomJS.run();
} else {
onload();
}
```
--------------------------------
### Copy Session Info to Clipboard
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example.template.html
Copies the text content of the element with ID 'session-info' to the user's clipboard. Provides console feedback on success or failure.
```javascript
function copySessionInfo() { const pre = document.getElementById('session-info'); const text = pre.textContent; navigator.clipboard.writeText(text).then(() => { console.log('Copied'); }).catch(err => { console.error('Failed to copy text: ', err); }); }
```
--------------------------------
### Log Custom Event with Content Items
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example.template.html
Logs a custom event with associated custom data and content items. Use this to track user interactions and attribute them to specific content.
```javascript
const eventName = "Custom Event Name";
const eventAndCustomData = {
"$id": "item_id",
"$name": "item_name",
"$category": "item_category",
"$price": 10.00,
"$currency": "USD",
"$product_variant": "Xl",
"$rating_average": 3.3,
"$rating_count": 5,
"$rating_max": 2.8,
"$creation_timestamp": 1499892854966
};
const contentItems = [eventAndCustomData];
const customerEventAlias = "my custom alias";
branch.logEvent( eventName, eventAndCustomData, contentItems, customerEventAlias, function(err) {
response.html(err || 'no error');
} );
```
--------------------------------
### Event Listener API
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/docs/web/2_table_of_contents.md
APIs for adding and removing event listeners.
```APIDOC
## Event Listener
### .addListener(event, listener)
Adds a listener for a specific event.
### .removeListener(listener)
Removes an existing event listener.
```
--------------------------------
### Display a Smart Banner
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example.template.html
Displays a smart banner to prompt users to download or open your mobile app. Configure various aspects like icons, text, and behavior.
```javascript
request.html(
'branch.banner({' +
'icon: ' + '"http://icons.iconarchive.com/icons/wineass/ios7-redesign/512/Appstore-icon.png",' +
'title: "Branch Demo App",' +
'description: "The Branch demo app!",' +
'data: {foo: "bar"},' +
'reviewCount: 1000,' +
'rating: 5,' +
'iframe: "true",' +
'showMobile: "true",' +
'showDesktop: "true",' +
'disableHide: "false",' +
'forgetHide: "false"' +
'});'
);
branch.banner( {
icon: 'http://icons.iconarchive.com/icons/wineass/ios7-redesign/512/Appstore-icon.png',
title: 'Demo App',
description: 'Branch Demo app!',
openAppButtonText: 'Open',
downloadAppButtonText: 'Download',
reviewCount: 1000, // Review count
rating: 5, // Average rating from 0 to 5 in increments of .5
iframe: true, // Show banner in an iframe if CSS on your page is conflicting
showMobile: true, // true by default, just set here for an example
showDesktop: true, // true by default, just set here for an example
disableHide: false, // false by default, just set here for an example
forgetHide: false // false by default, just set here for an example
}, // Banner Options
linkData // Link data or string of link
);
response.html('none');
```
--------------------------------
### Log Custom Event
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/event-v2-example.html
Logs a custom event with a specified name, custom data, content items, and an optional customer event alias. This allows for flexible event tracking beyond predefined events.
```javascript
var customData = { foo: "bar" };
var contentItems = [{ "$og_title": "Content Item", "$og_description": "Content description" }];
var eventName = $('#custom-event-name').val();
if (eventName.length == 0) {
alert('Please enter a custom event name.');
return;
}
var customerEventAlias = $('#customer-event-alias').val();
if (customerEventAlias.length == 0) customerEventAlias = null;
var requestText = "branch.logEvent('" + eventName + "', " + JSON.stringify(customData) + ", " + JSON.stringify(contentItems) + ", " + JSON.stringify(customerEventAlias) + ")";
$('#request').text(requestText);
$('#response').text('Waiting for response...');
branch.logEvent(
eventName,
customData,
contentItems,
customerEventAlias,
function(err) {
$('#response').text(JSON.stringify(err));
}
);
```
--------------------------------
### Track Commerce Event
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example.template.html
Logs a commerce event with associated custom data and content items. The request is indicated as 'See network tab' and the event is sent via the Branch SDK.
```javascript
function callLogEvent(eventName) {
request.html('See network tab');
const eventAndCustomData = {
"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"
};
const contentItems = [
{
"$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 &
```
--------------------------------
### Fetch Branch Data
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example.template.html
Calls the `branch.data()` method to retrieve associated data. Displays the request in the '#request' element and the response (or error) in the '#response' element.
```javascript
function callData() {
request.html('branch.data();');
branch.data(function(err, data) {
response.html(err || JSON.stringify(data));
});
}
```
--------------------------------
### Log Out User
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example.template.html
Calls the `branch.logout()` method to log out the current user. Displays 'branch.logout();' in the '#request' element and the response (or 'undefined') in the '#response' element.
```javascript
function callLogout() {
request.html('branch.logout();');
branch.logout(function(err, data) {
response.html(err || 'undefined');
});
}
```
--------------------------------
### Parse URL Query Parameters
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example.template.html
Extracts and returns all query parameters from the current URL as a key-value object. Useful for retrieving data passed via the URL.
```javascript
function getQueryParams() { const params = new URLSearchParams(window.location.search); const queryParams = {}; for (const [key, value] of params.entries()) { queryParams[key] = value; } return queryParams; }
```
--------------------------------
### Update Query Parameters with Branch SDK
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example.template.html
This JavaScript function updates URL query parameters for Branch SDK configuration, including branch key, API URL, and custom metadata. It parses JSON for metadata and branch view data, validates them, and updates the window location.
```javascript
const RESERVED_PARAMS = ['branch_key', 'api_url', '_branch_match_id', 'branchify_url', 'branchViewData'];
function getFinalValue(inputValue, documentKey) {
if (inputValue) return inputValue;
return document.getElementById(documentKey).value.trim();
}
function updateQueryParams(branchKey, apiUrl, script) {
let finalBranchKey = getFinalValue(branchKey, 'branchKeyInput');
let finalApiUrl = getFinalValue(apiUrl, 'apiUrlInput');
let finalMetadata = getFinalValue(null, 'metadataInput');
let finalBranchViewData = getFinalValue(null, 'branchViewDataInput');
if (!finalBranchKey && !finalApiUrl && !finalMetadata && !finalBranchViewData) {
alert('Please provide at least one value to update.');
return;
}
const url = new URL(window.location.href);
if (finalBranchKey) url.searchParams.set('branch_key', finalBranchKey);
if (finalApiUrl) url.searchParams.set('api_url', finalApiUrl);
// Clear existing metadata params
Array.from(url.searchParams.keys()).forEach(key => {
if (!RESERVED_PARAMS.includes(key)) {
url.searchParams.delete(key);
}
});
// Add new metadata params from JSON input
if (finalMetadata) {
try {
const metadata = JSON.parse(finalMetadata);
if (typeof metadata !== 'object' || metadata === null || Array.isArray(metadata)) {
alert('Metadata must be a JSON object, e.g., {"key": "value"}');
return;
}
for (const [key, value] of Object.entries(metadata)) {
url.searchParams.set(key, value);
}
} catch (e) {
alert('Invalid JSON in metadata field: ' + e.message);
return;
}
}
// Add branchViewData param from JSON input
if (finalBranchViewData) {
try {
const branchViewData = JSON.parse(finalBranchViewData);
if (typeof branchViewData !== 'object' || branchViewData === null || Array.isArray(branchViewData)) {
alert('Branch View Data must be a JSON object, e.g., {"data": {"$journeys_title": "value"}}');
return;
}
url.searchParams.set('branchViewData', JSON.stringify(branchViewData));
} catch (e) {
alert('Invalid JSON in Branch View Data field: ' + e.message);
return;
}
}
window.location.href = url.toString();
}
```
--------------------------------
### Generate a Deep Link
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example.template.html
Generates a deep link using the Branch SDK. This link can be used to direct users to specific content within your application.
```javascript
request.html('branch.link(' + JSON.stringify(linkData) + ');');
branch.link(linkData, function(err, link) {
response.html('' + link + '');
});
```
--------------------------------
### Deep Linking API
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/docs/web/2_table_of_contents.md
APIs for handling deep links and managing deep views.
```APIDOC
## Deep Linking
### .link(data, callback)
Generates a deep link with the provided data.
### .deepview(data, options, callback)
Manages deep view functionality with provided data and options.
### .deepviewCta()
Handles the Call To Action for deep views.
```
--------------------------------
### Event Tracking API
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/docs/web/2_table_of_contents.md
APIs for tracking custom events and commerce events within your application.
```APIDOC
## Event Tracking
### .track(event, metadata, callback)
Tracks a custom event with associated metadata.
### .logEvent(event, event_data_and_custom_data, content_items, callback)
Logs a detailed event with event data, custom data, and content items.
```
--------------------------------
### Extract Metadata from Query Parameters
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example.template.html
Filters query parameters to extract metadata, excluding reserved parameters. Returns null if no metadata is found.
```javascript
const RESERVED_PARAMS = []; function getMetadataFromQp() { const qp = getQueryParams(); const metadata = {}; for (const [key, value] of Object.entries(qp)) { if (!RESERVED_PARAMS.includes(key)) { metadata[key] = value; } } return Object.keys(metadata).length > 0 ? metadata : null; }
```
--------------------------------
### Set Branch API Response Callback
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/event-v2-example.html
Sets a callback function to handle responses from Branch API calls. This is useful for logging requests and responses, including errors.
```javascript
branch.setAPIResponseCallback(function(url, method, requestBody, error, status, responseBody) {
console.log('Request: ' + method + ' ' + url + ' body=' + JSON.stringify(requestBody));
if (error) {
console.log('Response: Error ' + error + '; status ' + JSON.stringify(status) + ' body=' + JSON.stringify(responseBody));
} else {
console.log('Response: status ' + JSON.stringify(status) + ' body=' + JSON.stringify(responseBody));
}
});
```
--------------------------------
### Revenue Analytics API
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/docs/web/2_table_of_contents.md
API for tracking commerce-related events for revenue analytics.
```APIDOC
## Revenue Analytics
### .trackCommerceEvent(event, commerce_data, metadata, callback)
Tracks a commerce event with associated commerce data and metadata.
```
--------------------------------
### Set Branch API Response Callback
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example-deepview.html
Sets a callback function to handle responses from the Branch API. This is useful for logging requests and responses, including errors.
```javascript
branch.setAPIResponseCallback(function(url, method, requestBody, error, status, responseBody) { console.log('Request: ' + method + ' ' + url + ' body=' + JSON.stringify(requestBody)); if (error) { console.log('Response: Error ' + error + '; status ' + JSON.stringify(status) + ' body=' + JSON.stringify(responseBody)); } else { console.log('Response: status ' + JSON.stringify(status) + ' body=' + JSON.stringify(responseBody)); } });
```
--------------------------------
### Update UI Labels with Branch Data
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example.template.html
Updates the text content of various labels on the page to display Branch Key, API URL, metadata, and Branch View Data. It parses JSON for Branch View Data if present.
```javascript
function setLabelText() { const keyLabel = document.getElementById('branchKeyLabel'); keyLabel.textContent = `Branch Key: ${getBranchKey()}`; const apiLabel = document.getElementById('apiUrlLabel'); apiLabel.textContent = `Api Url: ${getApiUrlLocal()}`; const metadataLabel = document.getElementById('metadataLabel'); const metadata = getMetadataFromQp(); if (metadata && Object.keys(metadata).length > 0) { metadataLabel.textContent = `Metadata: ${JSON.stringify(metadata)}`; } else { metadataLabel.textContent = 'Metadata (JSON):'; } const branchViewDataLabel = document.getElementById('branchViewDataLabel'); const qp = getQueryParams(); const branchViewData = qp['branchViewData']; if (branchViewData) { try { const parsed = JSON.parse(branchViewData); branchViewDataLabel.textContent = `Branch View Data: ${JSON.stringify(parsed)}`; } catch (e) { branchViewDataLabel.textContent = 'Branch View Data (JSON):'; } } else { branchViewDataLabel.textContent = 'Branch View Data (JSON):'; } }
```
--------------------------------
### Branch Banner CSS Styling
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/test/blob-banner.html
CSS rules for styling the Branch web banner, including transitions, layout, and theme variations.
```css
.branch-banner-is-active { -webkit-transition: all 0.375s ease; transition: all 00.375s ease; }
#branch-banner { width: 100%; z-index: 99999; font-family: Helvetica Neue, Sans-serif; -webkit-font-smoothing: antialiased; -webkit-user-select: none; -moz-user-select: none; user-select: none; -webkit-transition: all 0.25s ease; transition: all 00.25s ease; }
#branch-banner .button { border: 1px solid #ccc; background: #fff; color: #000; cursor: pointer; margin-top: 0px; font-size: 14px; display: inline-block; margin-left: 5px; font-weight: 400; text-decoration: none; border-radius: 4px; padding: 6px 12px; transition: all .2s ease; }
#branch-banner .button:hover { border: 1px solid #BABABA; background: #E0E0E0; color: #000; }
#branch-banner .button:focus { outline: none; }
#branch-banner * { margin-right: 4px; position: relative; line-height: 1.2em; }
#branch-banner-close { font-weight: 400; cursor: pointer; float: left; z-index: 2; padding: 0 5px 0 5px; margin-right: 0; }
#branch-banner .content { width: 100%; overflow: hidden; height: 76px; background: rgba(255, 255, 255, 0.95); color: #333; border-bottom: 1px solid #ddd; }
#branch-banner-close { color: #000; font-size: 24px; top: 14px; opacity: .5; transition: opacity .3s ease; }
#branch-banner-close:hover { opacity: 1; }
#branch-banner .title { font-size: 18px; font-weight: bold; color: #555; }
#branch-banner .description { font-size: 12px; font-weight: normal; color: #777; max-height: 30px; overflow: hidden; }
#branch-banner .icon { float: left; padding-bottom: 40px; margin-right: 10px; margin-left: 5px; }
#branch-banner .icon img { width: 63px; height: 63px; margin-right: 0; }
#branch-banner .reviews { font-size: 13px; margin: 1px 0 3px 0; color: #777; }
#branch-banner .reviews .star { display: inline-block; position: relative; margin-right: 0; }
#branch-banner .reviews .star span { display: inline-block; margin-right: 0; color: #555; position: absolute; top: 0; left: 0; }
#branch-banner .reviews .review-count { font-size: 10px; }
#branch-banner .reviews .star .half { width: 50%; overflow: hidden; display: block; }
#branch-banner .content .left { padding: 6px 5px 6px 5px; }
#branch-banner .vertically-align-middle { top: 50%; transform: translateY(-50%); -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); }
#branch-banner .details > * { display: block; }
#branch-banner .content .left { height: 63px; }
#branch-banner .content .right { float: right; height: 63px; margin-bottom: 50px; padding-top: 22px; z-index: 1; }
#branch-banner .right > div { float: left; }
#branch-banner-action { top: 17px; }
#branch-banner .content:after { content: ""; position: absolute; left: 0; right: 0; top: 100%; height: 1px; background: rgba(0, 0, 0, 0.2); }
#branch-banner .theme-dark.content { background: rgba(51, 51, 51, 0.95); }
#branch-banner .theme-dark #branch-banner-close { color: #fff; text-shadow: 0 1px 1px rgba(0, 0, 0, .15); }
#branch-banner .theme-dark .details { text-shadow: 0 1px 1px rgba(0, 0, 0, .15); }
#branch-banner .theme-dark .title { color: #fff; }
#branch-banner .theme-dark .description { color: #fff; }
#branch-banner .theme-dark .reviews { color: #888; }
#branch-banner .theme-dark .reviews .star span { color: #fff; }
#branch-banner .theme-dark .reviews .review-count { color: #fff; }
#branch-banner { position: absolute; }
#branch-banner .content .left .details .title { font-size: 12px; }
#branch-banner-mobile-action { white-space: nowrap; }
#branch-banner .content .left .details .description { font-size: 11px; font-weight: normal; }
@media only screen and (min-device-width: 320px) and (max-device-width: 350px) {
#branch-banner .content .right {
max-width: 120px;
}
}
@media only screen and (min-device-width: 351px) and (max-device-width: 400px) and (orientation: landscape) {
#branch-banner .content .right {
max-width: 150px;
}
}
@media only screen and (min-device-width: 401px) and (max-device-width: 480px) and (orientation: landscape) {
#branch-banner .content .right {
max-width: 180px;
}
}
body { margin: 0; }
```
--------------------------------
### Journeys Web To App API
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/docs/web/2_table_of_contents.md
APIs for managing Branch Journeys from web to app.
```APIDOC
## Journeys Web To App
### .setBranchViewData(data)
Sets data for Branch Journeys view.
### .closeJourney(callback)
Closes the current Branch Journey.
```
--------------------------------
### Branch Banner JavaScript Interaction
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/test/blob-interstitial.html
Handles click events for the close and accept buttons on the Branch banner. This script redirects the user to specific deep links based on the button clicked.
```javascript
(function (w, d) { var btnClose = d.getElementById('branch-banner-close'); if (btnClose) { btnClose.onclick = function(ev) { w.location.href='branch-cta://cancel'; ev.preventDefault(); }; } var btnAccept = d.getElementById('branch-mobile-action'); if (btnAccept) { btnAccept.onclick = function(ev) { w.location.href='branch-cta://accept'; ev.preventDefault(); }; } })(window, document);
```
--------------------------------
### Validate API URL for Branch
Source: https://github.com/branchmetrics/web-branch-deep-linking-attribution/blob/main/examples/example.template.html
Checks if a given API URL is valid and belongs to the branch.io domain. It ensures the URL uses HTTP or HTTPS protocol and has a hostname ending with '.branch.io'.
```javascript
function isAllowedApiUrl(apiUrl) {
if (!apiUrl) return false;
try {
const parsed = new URL(apiUrl);
return (parsed.protocol === 'http:' || parsed.protocol === 'https:') && parsed.hostname.toLowerCase().endsWith('.branch.io');
} catch (err) {
return false;
}
}
```