at.js functions

adobe.target.getOffer(options)

This function fires a request to get a Target offer.

Use with adobe.target.applyOffer() to process the response or use your own success handling. The options parameter is mandatory and has the following structure:

Key Type Required Description
mbox String Yes Mbox name
params Object No

Mbox parameters. An object of key-value pairs that has the following structure:

{ "param1": "value1", "param2": "value2"}

success Function Yes

Callback to be executed when we got a response from the server. The success callback function will receive a single parameter that represents an array of offer objects. Here is a success callback, example:

function handleSuccess(response){......}

See Responses below for details.

error Function Yes

Callback to be executed when we got an error. There are a couple of cases that are considered erroneous:

  • HTTP status code different from 200 OK
  • Response can not be parsed. For example we poorly constructed JSON or HTML instead of JSON.
  • Response contains the "error" key. For example an exception was thrown on the edge a request could not be properly processed. We could get an error when an mbox is blocked and we could not retrieve any content for it etc.

The error callback function will receive two parameters: status and error. Here is an error callback example:

function handleError(status, error){......}

See Error Responses below for details.
timeout Number No

Timeout in milliseconds. If not specified, the default timeout in at.js will be used. The default timeout can be set from the Target UI under Setup > Implementation > Edit Mbox.js Settings > Timeout.

Examples

Adding parameters with getOffer() and using applyOffer() for success-handling:

adobe.target.getOffer({  
  "mbox": "target-global-mbox",
  "params": {
     "a": 1,
     "b": 2
  },
  "success": function(offer) {          
        adobe.target.applyOffer( { 
           "mbox": "target-global-mbox",
           "offer": offer 
        } );
  },  
  "error": function(status, error) {          
      console.log('Error', status, error);
  }
});

Adding parameters and profile parameters with getOffer() and using applyOffer() for success-handling:

adobe.target.getOffer({  
  "mbox": "target-global-mbox",
  "params": {
     "a": 1,
     "b": 2,
     "profile.age": 27,
     "profile.gender": "male"
  },
  "success": function(offer) {          
        adobe.target.applyOffer( { 
           "mbox": "target-global-mbox",
           "offer": offer 
        } );
  },  
  "error": function(status, error) {          
      console.log('Error', status, error);
  }
});

Using custom timeout and custom success-handling with getOffer():

"YOUR_OWN_CUSTOM_HANDLING_FUNCTION" is a placeholder for a function the customer would define.

adobe.target.getOffer({    
  "mbox": "target-global-mbox",  
  "success": function(offer) {
    YOUR_OWN_CUSTOM_HANDLING_FUNCTION(offer);  
  },
  "error": function(status, error) {                
    console.log('Error', status, error);  
  },  
  "timeout": 2000
});

Responses

The response parameter passed to the success callback will be an array of actions. An action is an object that usually has the following format:

Name Type Description
action String

Type of action to be applied to the identified element.

selector Sting

Represents a Sizzle selector.

cssSelector String

DOM native selector, used for element pre-hiding.

content String

The content to be applied to the identified element.

Example

{
    "sessionId": "1444512212156-384616",
    "tntId": "1444512212156-384616.17_35",
    "offers": [{
        "plugins": ["<script type=\"text/javascript\">\r\n/*mboxHighlight+ (1of2) v1 ==> Response Plugin*/\r\nwindow.ttMETA=(typeof(window.ttMETA)!='undefined')?window.ttMETA:[];window.ttMETA.push({'mbox':'target-global-mbox','campaign':'at: redirect ootb','experience':'Experience B','offer':'/at_redirect_ootb/experiences/1/pages/0/1442082890250'});window.ttMBX=function(x){var mbxList=[];for(i=0;i<ttMETA.length;i++){if(ttMETA[i].mbox==x.getName()){mbxList.push(ttMETA[i])}}return mbxList[x.getId()]}\r\n</script>"],
        "actions": {
            "content": [{
                "passMboxSession": false,
                "selector": "body",
                "action": "redirect",
                "url": "http://example.com/04.html",
                "includeAllUrlParameters": true
            }]
        }
    }]
}

Error Responses

The "status" and "error" parameters passed to the error callback will have the following format:

Name Type Description
status String

Represents the error status. This parameter can have the following values:

  • timeout

    Indicates that the request timed out

  • parseerror

    Indicates that the response could not be parsed, for example if we receive HTML or plain text instead of JSON

  • error

    Indicates a general error like we received HTTP status different from 200 OK

error String

Contains additional data like exception message or anything else that might be useful for troubleshooting.

[Back to Top]

adobe.target.applyOffer(options)

This function is for applying the response content.

Note: applyOffer requires the mbox parameter. If no mbox name is specified, an error occurs.

The options parameter is mandatory and has the following structure:

Key Type Required Description

mbox

String

Yes

Mbox name

With at.js 1.3.0 (and later) Target enforces that the mbox key is used. This key has been required in the past, but Target now enforces its use to ensure that Target has proper validation and customers are using the function correctly.

selector

String or DOM Element

No

HTML element or CSS selector used to identify the HTML element where Target should place the offer content. If selector is not provided, Target assumes that the HTML element we should use is HTML HEAD.

offer

Array

Yes

An array actions that should be applied to the element.

Example

The following example shows how to use getOffer and applyOffer together:

adobe.target.getOffer({  
  "mbox": "mbox",  
  "success": function(offers) {          
        adobe.target.applyOffer( { 
           "mbox": "mbox",
           "offer": offers 
        } );
  },  
  "error": function(status, error) {          
      if (console && console.log) {
        console.log(status);
        console.log(error);
      }
  },
 "timeout": 5000
});

[Back to Top]

adobe.target.trackEvent(options)

This function fires a request to report user actions, such as clicks and conversions. It does not deliver activities in the response.

These event-tracking mbox calls can then be used to define metrics in activities. For more information, see Success metrics and Track Conversions.

Here are the API details:

Key Type Required Description
mbox String Yes

Mbox name

selector String No

CSS selectors used to find the HTML elements. The event listeners will be attached to found elements.

type String No

Represents a registered event type. It can be both HTML known events like: click, mousedown ,etc., as well as custom HTML events.

preventDefault Boolean No

Indicates whether to use event.preventDefault() in the event listener callback. Defaults to false.

Note: Only form[submit], a[click] are supported. Other scenarios are not supported due to complexity and huge amount of scenarios to support.
params Object No

Mbox parameters. An object of key-value pairs that has the following structure:

{ "param1": "value1", "param2": "value2"}

timeout Number No

Timeout in milliseconds.

If not specified, default value is used:

{...timeoutInSeconds: 0.15...}

success Function No

A callback function used to signal that event has been reported.

error Function No

A callback function used to signal that event could not be reported.

Example

<a href="http://asite.com">click me!</a> 

plus javaScript code to assign trackEvent:

<script>
$('a').click(function(event){
  adobe.target.trackEvent({'mbox':'homePageHero'})
});
</script> 

Or:

adobe.target.trackEvent({
    "mbox": "clicked-cta",
    "params": {
        "param1": "value1"
    }
});
Note: In case the mandatory fields are not set, no request is executed, and an error is thrown.

[Back to Top]

mboxCreate(mbox,params)

Executes a request and applies the offer to the closest DIV with mboxDefault class name.

This function is built into at.js mostly to ease the transition from mbox.js to at.js. A newer alternative to mboxCreate() is adobe.target.getOffer()/adobe.target.applyOffer() or the Angular directive.

Example

<div class="mboxDefault">
  default content to replace by offer
</div>
<script>
  mboxCreate('mboxName','param1=value1','param2=value2');
</script>

Notes

mboxCreate() now uses the "json" endpoint instead of the "standard" endpoint and fires asynchronously. Because of this:

  • Debugging is a little different.
  • Avoid offer code requiring synchronous, blocking calls.

    For example, offers that set JavaScript variables that are used by site code or other mboxes that come later on the page.

  • Be sure to have a <div class="mboxDefault"></div> before invoking mboxCreate(), because at.js will not add one for you.
  • Empty, top-of-page mboxCreate() functions are not recommended as a global mbox.

    The auto-created global mbox in at.js is a better option because it fires from the <head> and can return content earlier.

[Back to Top]

mboxDefine() and mboxUpdate()

Define and update an mbox.

Note: mboxDefine() and mboxCreate() are tied to HTML DIV elements where the offer should be displayed. These HTML DIV elements should have the mboxDefault class. If the HTML elements won't have this class attached, you could see some noticeable flicker.

mboxDefine

Creates an internal mapping between a nodeId and an mbox name, but does not execute the request. Used in conjunction with mboxUpdate(). Built into at.js mostly to ease the transition from mbox.js to at.js.

mboxUpdate

Executes the request and applies the offer to the element identified by the nodeId in the mboxDefine(). Can also be used to update an mbox initiated by mboxCreate. Built into at.js mostly to ease the transition from mbox.js to at.js. mboxDefine()/mboxUpdate() could be replaced by adobe.target.getOffer() and adobe.target.applyOffer() using the selector option.

Example

<div id="someId" class="mboxDefault"></div>
<script>
 mboxDefine('someId','mboxName','param1=value1','param2=value2');
 mboxUpdate('mboxName','param3=value3','param4=value4');
</script>

[Back to Top]

targetGlobalSettings()

You can override settings in the at.js library using targetGlobalSettings(), rather than configuring the settings in the Target Standard/Premium UI or by using REST APIs.

There are use cases, especially when at.js is delivered via Dynamic Tag Management (DTM) when you would like to override some of the settings.

Settings

You can override the following settings:

Settings Type Default Value Description

clientCode

String

Value set via UI

Represents client code

serverDomain

String

Value set via UI

Represents Target edge server

cookieDomain

String

If possible set to top level domain

Represents the domain used when saving cookies

crossDomain

String

Value set via UI

Indicates whether cross-domain tracking is enabled or not.

The allowed values are:

  • disabled

  • enabled

  • x-only

timeout

Number

Value set via UI

Represents Target edge request timeout

globalMboxAutoCreate

Boolean

Value set via UI

Indicates whether the global mbox request should be fired or not

visitorApiTimeout

Number

2000 ms = 2 s

Represents the Visitor API request timeout

enabled

Boolean

true

Indicates whether at.js as library is enabled, meaning if it should execute anything or not. The main use case for this setting being opt-out cookies or other custom decisions that would disable at.js functionality

defaultContentHiddenStyle

String

visibility: hidden

Used only for wrapping mboxes that use DIV with class name "mboxDefault" and are executed via mboxCreate(), mboxUpdate(), or mboxDefine() to hide default content

defaultContentVisibleStyle

String

visibility: visible

Used only for wrapping mboxes that use DIV with class name "mboxDefault" and are executed via mboxCreate(), mboxUpdate(), or mboxDefine() to reveal applied offer if any or default content

bodyHiddenStyle

String

body { opacity: 0 }

Used only when globalMboxAutocreate === true to minimize the chance of flicker

For more information, see How at.js manages flicker.

bodyHidingEnabled

Boolean

true

Used to control flicker when target-global-mbox is used to deliver offers created in the Visual Experience Composer, also known as visual offers

imsOrgId

String

IMS ORG ID

Represents the IMS ORG ID

secureOnly

Boolean

false

Indicates whether at.js should use HTTPS only or be allowed to switch between HTTP and HTTPS based on the page protocol.

overrideMboxEdgeServer

Boolean

false

Indicates if we should use <clientCode>.tt.omtrdc.net domain or mboxedge<clusterNumber>.tt.omtrdc.net domain. If this value is true, mboxedge<clusterNumber>.tt.omtrdc.net domain will be saved to a cookie

overrideMboxEdgeServerTimeout

Number

1860000 => 31 minutes

Indicates the cookie lifetime that contains the mboxedge<clusterNumber>.tt.omtrdc.net value.

optoutEnabled

Boolean

false

Indicates whether Target should call the Visitor API isOptedOut() function. This is part of Device Graph enablement.

selectorsPollingTimeout

Number

5000 ms = 5 s

In at.js 0.9.6, Target introduced this new setting that can be overridden via targetGlobalSettings,

selectorsPollingTimeout represents how long the client is willing to wait for all the elements identified by selectors to appear on the page.

Activities created via the Visual Experience Composer (VEC) have offers that contain selectors.

dataProviders

See Data Providers below.

See Data Providers below.

See Data Providers below.

Usage

This function can be defined before at.js is loaded or in Setup > Implementation > Edit at.js Settings > Code Settings > Library Header.

The Library Header field allows you to enter free-form JavaScript. The customization code should look something similar to the following example:

window.targetGlobalSettings = { 
   timeout: 200, // using custom timeout 
   visitorApiTimeout: 500, // using custom API timeout 
   enabled: document.location.href.indexOf('http://www.adobe.com') >= 0 // enabled ONLY on adobe.com 
};

Data Providers

This setting lets customers gather data from third-party data providers, such as Demandbase, BlueKai, and custom services, and pass the data to Target as mbox parameters in the global mbox request. It supports the collection of data from multiple providers via async and sync requests. Using this approach makes it easy to manage flicker of default page content, while including independent timeouts for each provider to limit the impact on page performance

Note: Data Providers requires at.js 1.3 or later.

The following videos contain more information:

Video Description

Using Data Providers in Adobe Target

Data Providers is a capability that allows you to easily pass data from third parties to Target. A third party could be a weather service, a DMP, or even your own web service. You can then use this data to build audiences, target content, and enrich the visitor profile.

Implement Data Providers in Adobe Target

Implementation details and examples of how to use Adobe Target's dataProviders feature to retrieve data from third-party data providers and pass it in the Target request.

The window.targetGlobalSettings.dataProviders setting is an array of data providers.

Each data provider has the following structure:

Key Type Description

name

String

Name of provider.

version

String

Provider version. This key will be used for provider evolution.

timeout

Number

Represents the provider timeout if this is a network request.

This key is optional.

provider

Function

The function that contains the provider data fetching logic.

The function has a single required parameter: callback. The callback parameter is a function that should be invoked only when the data has been successfully fetched or there is an error.

The callback expects two parameters:

  • error: Indicates if an error occurred. If everything is OK, then this parameter should be set to null.

  • params: A JSON object, representing the parameters that will be sent in a Target request.

The following example shows where the data provider is using sync execution:

var syncDataProvider = {
  name: "simpleDataProvider",
  version: "1.0.0",
  provider: function(callback) {
    callback(null, {t1: 1});
  }
};
 
window.targetGlobalSettings = {
  dataProviders: [
    syncDataProvider
  ]
};

After at.js processes window.targetGlobalSettings.dataProviders, the Target request will contain a new parameter: t1=1.

The following is an example if the parameters that you want to add to the Target request are fetched from a third-party service, such as Bluekai, Demandbase, and so forth:

var blueKaiDataProvider = {
   name: "blueKai",
   version: "1.0.0",
   provider: function(callback) {
      // simulating network request
     setTimeout(function() {
       callback(null, {t1: 1, t2: 2, t3: 3});
     }, 1000);
   }
}
 
window.targetGlobalSettings = {
   dataProviders: [
      blueKaiDataProvider
   ]
};

After at.js processes window.targetGlobalSettings.dataProviders, the Target request will contain additional parameters: t1=1, t2=2 and t3=3.

The following example uses data providers to collect weather API data and send it as parameters in a Target request. The Target request will have additional params, such as country and weatherCondition.

var weatherProvider = {
      name: "weather-api",
      version: "1.0.0",
      timeout: 2000,
      provider: function(callback) {
        var API_KEY = "caa84fc6f5dc77b6372d2570458b8699";
        var lat = 44.426767399999996;
        var lon = 26.1025384;
        var url = "//api.openweathermap.org/data/2.5/weather?lang=en";
        var data = {
          lat: lat,
          lon: lon,
          appId: API_KEY
        }

        $.ajax({
          type: "GET",
                url: url,
          dataType: "json",
          data: data,
          success: function(data) {
            console.log("Weather data", data);
            callback(null, {
              country: data.sys.country,
              weatherCondition: data.weather[0].main
            });
          },
          error: function(err) {
            console.log("Error", err);
            callback(err);
          }
        });        
      }
    };

    window.targetGlobalSettings = {
      dataProviders: [weatherProvider]
    };

Consider the following when working with the dataProviders setting:

  • If the data providers added to window.targetGlobalSettings.dataProviders are async, they will be executed in parallel. The Visitor API request will be executed in parallel with functions added to window.targetGlobalSettings.dataProviders to allow a minimum wait time.

  • at.js won't try to cache the data. If the data provider fetches data only once, the data provider should make sure that data is cached and, when the provider function is invoked, serve the cache data for the second invocation.

[Back to Top]

targetPageParams()

This method allows you to attach parameters to the global mbox from outside of the request code.

This function is very useful for including the same set of parameters on multiple mbox calls. The function needs to be defined by the customer. It should return an array of parameters that will be passed only to the global mbox request. This function can be defined before at.js is loaded or in Setup > Implementation > Edit at.js Settings > Code Settings > Library Header.

You can pass in parameters to target-global-mbox using the targetPageParams() function in any of the following ways:

  • An ampersand-delimited list
  • An array
  • A JSON object

Examples

Ampersand-delimited list (values must be URL encoded):

function targetPageParams() {
    return "param1=value1&param2=value2&p3=hello%20world";
}

Array (values do not need to be URL encoded):

targetPageParams = function() {
     return ["a=1", "b=2", "c=hello world"];
};

JSON (values do not need to be URL encoded):

targetPageParams = function() {
  return {
    "a": 1,
    "b": 2,
    "profile": {
        "age": 26,
        "country": {
          "city": "San Francisco"
        }
      }
  };
};

[Back to Top]

targetPageParamsAll()

This method allows you to attach parameters to all mboxes from outside of the request code.

This is very useful for including the same set of parameters on multiple mbox calls. The function needs to be defined by the customer. It should return an array of parameters that will be passed to all mbox requests on the page. This function can be defined before at.js is loaded or in Setup > Implementation > Edit at.js Settings > Code Settings > Library Header.

You can pass in parameters to target-global-mbox using the targetPageParamsAll() function in any of the following ways:

  • An ampersand-delimited list
  • An array
  • A JSON object

Examples

Ampersand-delimited list (values must be URL encoded):

function targetPageParamsAll() {
    return "param1=value1&param2=value2&p3=hello%20world";
}

Array (values do not need to be URL encoded):

targetPageParamsAll = function() {
     return ["a=1", "b=2", "c=hello world"];
};

JSON (values do not need to be URL encoded):

targetPageParamsAll = function() {
  return {
    "a": 1,
    "b": 2,
    "profile": {
        "age": 26,
        "country": {
          "city": "San Francisco"
        }
      }
  };
};

[Back to Top]

registerExtension()

Provides a standard way to register a specific extension.

The options parameter is mandatory and has the following structure:

Key Type Required Description

name

String

Yes

Extension name.

modules

Array[String]

Yes

An array of strings representing requested module names.

register

Function

Yes

A function used to initialize and build the extension. This function receives arguments based on modules array.

Notes:

  • If one of the parameters is not provided, an exception is thrown.

  • If the modules array is empty, an exception is thrown.

For more information and examples of how to use registerExtension, see the Adobe Experience Cloud Target atjs Extensions page on GitHub.

Settings Module Methods

Key Type Description

clientCode

String

Client code

serverDomain

String

Edge server domain

globalMboxName

String

Target global mbox name

globalMboxAutoCreate

Boolean

Indicates if auto-create is enabled or not

timeout

Number

Request timeout

Logger Module Methods

Key Type Description

log

Function

Logs the variable list of arguments to the browser console, if it exists. It is activated only when mboxDebug=true is passed to the URL.

error

Function

Logs the variable list of arguments to the browser console. It is activated only when there are serious errors, such as network timeout, HTML node not found, etc.

[Back to Top]

at.js custom events

Information about at.js custom events, which lets you know when an mbox request or offer fails or succeeds.

Historically, mbox.js didn't let other JavaScript code that runs on the page know what happens behind the scenes. With the advancement of at.js, we had a unique opportunity to fix this issue.

According to our customers there are several scenarios that they would like to be notified of, including:

  • An mbox request failed due to timeout, wrong status code, JSON parse error, etc.

  • An mbox request succeeded.

  • Offer rendering failed due to wrapping mbox element missing, selector can not be found, etc.

  • Offer rendering succeeded. DOM changes have been applied.

Pre-defined events have a structure that allows you to extract the required data, based on event type.

To make sure that events can be used in different scenarios, the custom events have a payload object that is assigned to the detail property of the event object (that is passed to the handler). Also to avoid passing strings as event names, the events are exposed as constants using adobe.target.event namespace.

Structure

Key Type Description

type

String

There are several scenarios in which you would like to be notified to help in tracing, debugging, and customizing interaction with at.js.

Each custom event listed below has two formats: a "constant" and a "string value."

  • Constants: Prepended with adobe.target.event., presented in all caps, and contain underscore characters. To subscribe to custom events after at.js loads but before the mbox response has been received, use the constant.

  • String Values: Lowercase and contain dashes. To subscribe to custom events before at.js loads, use the string value.

Request Failed

Constant: adobe.target.event.REQUEST_FAILED

Sting value: at-request-failed

Description: An mbox request failed due to timeout, wrong status code, JSON parse error, etc.

Request Succeeded

Constant: adobe.target.event.REQUEST_SUCCEEDED

String Value: at-request-succeeded

Description: An mbox request was successful.

Content Rendering Failed

Constant: adobe.target.event.CONTENT_RENDERING_FAILED

String Value: at-content-rendering-failed

Description: Offer rendering failed due to wrapping mbox element missing, selector can not be found, etc.

Content Rendering Succeeded

Constant: adobe.target.event.CONTENT_RENDERING_SUCCEEDED

String Value: at-content-rendering-succeeded

Description: Offer rendering was successful. DOM changes have been applied.

Library Loaded

Constant: adobe.target.event.LIBRARY_LOADED

String Value: at-library-loaded

Description: This event is ideal to track when at.js has been fully loaded. You can use this event to customize global mbox execution. You can also use this event to disable the global mbox and then listen for this event to fire the global mbox later.

Request Start

Constant: adobe.target.event.REQUEST_START

String Value: at-request-start

Description: This event is fired before an HTTP request is executed. You can use this event for performance measurements using the Resource Timing API.

Content Rendering Start

Constant: adobe.target.event.CONTENT_RENDERING_START

String Value: at-content-rendering-start

Description: This event is fired before selector polling is started and content is rendered to the page. You can use this event to track the content rendering progress.

Content Rendering No Offers

Constant: adobe.target.event.CONTENT_RENDERING_NO_OFFERS

String Value: at-content-rendering-no-offers

Description: This event is fired when there are no offers returned.

Content Rendering Redirect

Constant: adobe.target.event.CONTENT_RENDERING_REDIRECT

String Value: at-content-rendering-redirect

Description: This event is fired when an offer is a redirect and Target will redirect to a different URL.

mbox

String

mbox name

message

String

Contains human-readable description, such as what happened, the error message, etc.

tracking

Object

Contains the sessionId and deviceId. In some cases, deviceId could be missing because Target couldn't retrieve it from edge server.

Usage

document.addEventListener(adobe.target.event.REQUEST_SUCCEEDED, function(event) {
  console.log('Event', event);
});

Training Video

Watch the following video to learn how to use Response Tokens and at.js Custom Events to share profile information from Target to third-party systems.

[Back to Top]