JavaScript Front-end API

The BlueConic JavaScript Front-end API allows you to create BlueConic plugins that run in the browser of the visitor and have them use information from BlueConic.

For tutorials on how to build front-end plugins, see Getting Started.

 


BlueConicClient Methods

The BlueConicClient class represents the BlueConic application on the clientside. It controls the loading of interactions, profiles and it triggers events. The object is injected in the init(blueConicClient, interactionContext) function of a plugin, where it is typically stored in a variable for later use.

var InteractionTypeImpl = InteractionType.extend({

  // Called every time a new interaction of this type is created.
  init: function(blueConicClient, interactionContext) {
    this.blueConicClient = blueConicClient;
    this.interactionContext = interactionContext;
  }
});

createEvent(eventtype, interactionId, caller, onSuccess)

This method triggers a new event. Events are needed to register certain actions of your visitors. For example when a visitor clicks on a banner you want to register this click so you can track which banners have been clicked. There are three BlueConic specific events which you can use for your interaction type: CLICK, VIEW and CONVERSION:

  • The CLICK event type is intended to be triggered when a visitor clicks on an interaction.
  • The VIEW event type can be triggered when an interaction is shown to a visitor.
  • The CONVERSION event type is used to register a conversion, for example when the visitor actually buys a product.

It is also possible to create custom events that dialogues can subscribe to on the "When" tab. The name of a custom event has to match the id of an eventType in the XML definition file for a plugin. When createEvent() is invoked to create a custom event, all dialogues configured to display on this event on their "When" tab will be executed.

BlueConic by default registers a VIEW event when an interaction is triggered. When you trigger your own VIEW event from an interaction type you might look at manual view counting to see how to prevent this default behavior. See Conversion URL to get a good understanding of the CONVERSION event. You may also take a look at the interaction line graph to see how CLICK, VIEW and CONVERSION events are related.

Parameters

Name Data Type Description
eventtype string The eventtype to trigger.
interactionId string The ID of the interaction for which you want to trigger the event.
caller object Specifies the scope of the onSuccess function.
onSuccess function A function that is called after the event was successfully triggered.

Returns

Nothing.

Example

// Note that each interaction receives a context object when initialized.
var interactionId = this.interactionContext.getInteractionId();

// Throw a BlueConic CLICK event, e.g. at the onclick of a banner.
this.blueConicClient.createEvent('CLICK', interactionId, this, function(result) {
  console.log('click event successfully registered');
});

// Throw a custom "inactivity" event for dialogues subscribed to it on the "When" tab
this.blueConicClient.createEvent('inactivity', interactionId, this, function(result) {
  // All dialogues subscribed to the "inactivity" event have now been executed (again)
console.log('inactivity event successfully registered'); });

getBaseURL(interactionTypeId)

Returns the base URL for the specified interactionTypeId. This can be used to refer to static resources from the interaction type (e.g. images, JavaScript libraries or stylesheets). The base URL is the URL of the interaction type XML definition without the filename. For example, if the URL was 'http://plugins.mysite.com/content/1.0.0/index.xml' then the base URL for the content interaction type is 'http://plugins.mysite.com/content/1.0.0/'. ThegetBaseURL method returns the URL with the appropriate protocol (http or https). When SSL is required but not available the "http" protocol is used as fallback.

Look at managing plugins for more information.

Parameters

Name Data Type Description
interactionTypeId string The identifier of the interaction type from which you want to retrieve the static prefix. Only the ID of the current interaction type or interaction types it has a dependency on can be retrieved.

Returns

Returns the base URL (string) or undefined if the interactionType was not found.

Example

In the example below, the file 'logo.gif' is placed on the web server, in the same directory as the interaction type XML definition of the interaction type with the id 'content':

init : function(blueConicClient, context) {
  // get an absolute url to a resource from the interactiontype
  // the protocol of the baseURL will be "https:" when the page is requested over https:
  var baseURL = blueConicClient.getBaseURL('content');
  var imageLocation = baseURL + 'logo.gif';
  // imageLocation is now http://plugins.mysite.com/content/1.0.0/logo.gif
}

In the example below, the interaction type is placed on a web server with SSL support and the interaction runs at https://foo.com:

init : function(blueConicClient, context) {
  // get an absolute url to a resource from the interactiontype
  // the protocol of the baseURL will be "https:" when the page is requested over https:
  var baseURL = blueConicClient.getBaseURL('content');
  var imageLocation = baseURL + 'logo.gif';
  // imageLocation is now https://plugins.mysite.com/content/1.0.0/logo.gif
}

getChannelId()

Returns the id of the current channel.

Parameters

None.

Returns

The id of the current channel (string).

Example

init: function(blueConicClient, interactionContext) {
  var hostname = blueConicClient.getHostname();
}

getCurrentDate()

Returns the current date. In the Journey Simulator this will return the simulated date if that is defined.

Parameters

None.

Returns

Returns the date.

Example

init: function(blueConicClient, interactionContext) {
  var currentDate = blueConicClient.getCurrentDate();
}

getHostname()

Returns the BlueConic hostname. E.g. "localhost:3737".

Parameters

None.

Returns

Returns the BlueConic hostname.

Example

var hostname = blueConicClient.getHostname();

getInteractions()

Returns the dialogues and variants that where triggered for the current pageview. To enable this feature, the option "Expose the dialogues that were visible to the visitor" on the Privacy Settings tab must be enabled.

Parameters

None

Returns

An array containing the dialogues and variants.

Example

var interactions = blueConicClient.getInteractions();

if (interactions.length > 0) {
  // display the names of the triggered interactions
  for (var i = 0; i < interactions.length; i++) {
    var interactionName = (function() {
      if (interactions[i].variantName) {
        return interactions[i].name + ' / ' + interactions[i].variantName;
      } else {
        return interactions[i].name;
      }
    }());

    alert(interactionName);
  }
}

getIPAddress()

Returns the IP address of the visitor.

Parameters

None.

Returns

The IP address of the visitor (string).

Example

var blueConicClient = new BlueConicClient();
var ipAddress = blueConicClient.getIPAddress();

getProfileProperties(caller, onSuccess)

Returns the id, labels, and permission levels for all profile properties.

Parameters

Name Data Type Description
caller object The calling object.
onSuccess function The onSuccess function.

Returns

Nothing.

Example

blueConicClient.getProfileProperties(this, function(resultMap) {
  var property = resultMap['browsername'];
  var message = 'Permission level for ' + property.labels['en_US'] + ' is ' + property.permissionLevel;
  alert(message); // Permission level for Browser Name is ANONYMOUS
});

getSegments()

Returns all associated segments for the current profile. To enable this feature, the option "Expose the segments that the visitor is part of" on the Privacy Settings tab must be enabled.

Parameters

None

Returns

An array containing Segment objects. Each Segment object has a 'name' attribute. 

Example

var segments = blueConicClient.getSegments();

if (segments.length > 0) {
  // display the names of the currently matching segments
  var segmentNames = new Array();
for (var i = 0; i < segments.length; i++) {
segmentNames.push(segments[i].name);
}
console.log(segmentNames.join(',')); }

handlePageView()

Executes the listeners and dialogues based on the current URL. BlueConic will do this automatically upon loading a page. This function is typically called after taking javascript action that influenced the URL of the page after it was loaded, for example a "hashchange" or "popstate" event. Dialogues that already have been executed will not be executed again, Listeners will be executed again.

Parameters

None.

Returns

Nothing.

Example

var blueConicClient = new BlueConicClient();

// Rewrite the URL without reloading the page
window.history.pushState(newBody, newTitle, "/new-url");

// Handle page view based on the new URL
blueConicClient.handlePageView();

isInEditMode()

Returns true when the edit mode of BlueConic is active.

Parameters

None.

Returns

True or false depending on whether the edit mode is active.

Example

if (this.blueConicClient.isInEditMode()) {
  // The inside of the lightbox is editable
  this.blueConicClient.setEditableNode(".fancybox-inner", { colorScheme: "light" });
}

isInSimulatorMode()

Returns whether the simulator is active.

Parameters

None.

Returns

True or false depending on whether the simulator is active.

Example

var simActive = blueConicClient.isInSimulatorMode();

setEditableNode(domElement, options)

The function setEditableNode is used to set the DOM element that should be used to highlight as being editable. For example, if you create a lightbox you only want the contents of the lightbox to be editable instead of the entire lightbox including the surrounding decoration.

If you do not explicitly set an editable node with this function, the node indicated by the position will be used as editable node by default.

Parameters

Name Data Type Description
domElement object The DOM element that contains the content that can be edited.
options object Optional extra settings for the editable node. Supported options are:
Option Value Description
colorScheme "light", "dark" Use the indicated color scheme for the editable node.
positionName Any string The name of the position. This will be displayed in the bar with the "Edit" button.

Returns

Nothing.

Example

blueConicClient.setEditableNode($(".fancybox-inner").get(0),
    { colorScheme: "light" }
  );

event.publish(eventName, eventContext)

Publishes an event. The eventContext is an optional array that can be used to pass on parameters to subscribers of the event.

Note that this custom event can be listened to from within BlueConic by defining a custom event listening rule.

Parameters

Name Data Type Description
eventName string The name of the event to publish.
eventContext array An Array containing relevant attributes. This argument is optional.

Returns

Nothing.

Example

// Publish the "ON_BANNER_CLICK" event when myBanner is clicked
var banner = document.getElementById('#myBanner');
banner.addEventListener("click", function() {
  blueConicClient.event.publish('ON_BANNER_CLICK', [banner, 'banner_name']);
});

event.subscribe(eventName, handlerObject, handlerFunction)

Subscribes to an event published using event.publish(eventName, eventContext). When the event is published the handlerFunction is called with the handlerObject as context. The handlerFunction is called with two arguments:

  • event which is the name of the published event (eg: 'ON_BANNER_CLICK').
  • context an object which holds the context of the published event or null when the event was published without context.

When you subscribe to an event you will also be notified for already published events.

Parameters

Name Data Type Description
eventName string The name of the event to subscribe to.
handlerObject object Specifies the scope of the handler function.
handlerFunction function A function that is called after the event is thrown.

Returns

Nothing.

Example

blueConicClient.event.subscribe('myEventName', this, function(event, context) {
  alert('event handled');
});
// Publish the "ON_BANNER_CLICK" event when myBanner is clicked
var banner = document.getElementById('#myBanner');
banner.addEventListener("click", function() {
  blueConicClient.event.publish('ON_BANNER_CLICK', [banner, 'banner_name']);
});

// Subscribe to the "ON_BANNER_CLICK"
blueConicClient.event.subscribe('ON_BANNER_CLICK', this, function(event, context) {
  // Handle the event "ON_BANNER_CLICK"
  alert('event ' + event + ' handled for ' + context[1]);
});

functions.setLocaleFunction(localeFunction)

The setLocaleFunction is used to set the localeFunction. The default localeFunction use the browser language.
When implementing your own localeFunction make sure that this localeFunction is set before getParameters() is called. The best place to set alocaleFunction is the init method of an interaction type. Please note that all interactions share the same localeFunction.

Look at managing languages for more information about configuring languages.

Parameter

Name Data Type Description
localeFunction function A function which returns the language to use on the client

Returns

Nothing.

Example

var localeFunction = function(parameters, defaultLocale) {
  // determine the language based on the browser string
  var browserlanguage = window.navigator.language;

  if (browserlanguage) {
    browserlanguage = browserlanguage.replace('-', '_');
    browserlanguage = browserlanguage.toLowerCase();
    return browserlanguage;
  }

  // return the default value
  return defaultLocale;
}

blueConicClient.functions.setLocaleFunction(localeFunction);

json.parse(json)

Parses the given JSON string to an object. The browser's parse method is used when available. When not available, the JSON2 library is used to parse the JSON.

Parameters

Name Data Type Description
json String The JSON string to parse.

Returns

An object.

Example

var json = '{"foundation":"Mozilla","model":"box","week":45,"transport":"car","month":7}';
var object = blueConicClient.json.parse(json);
alert(object.transport); // car

json.stringify(object, replacer, space)

Stringifies the given object to a JSON string. The browser's stringify method is used when available. When not available, the JSON2 library is used to stringify the object.

Parameters

Name Data Type Description
object Object The object to stringify.
replacer function (Optional) When provided, the function is called for every key and value added to the final result.
space String (Optional) The space argument controls the spacing in the final string. If it is a number, successive levels in the stringification will each be indented by the number of spaces specified (up to 10). If it is a string, successive levels will indented by this string (or the first ten characters of it).

Returns

JSON.

Example

var foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7};
var jsonString = blueConicClient.json.stringify(foo);
alert(jsonString); // {"foundation":"Mozilla","model":"box","week":45,"transport":"car","month":7}
function censor(key, value) {
  if (typeof(value) == "string") {
    return undefined;
  }
  return value;
}

var foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7};
var jsonString = blueConicClient.json.stringify(foo, censor);
alert(jsonString); // {"week":45,"month":7}
function censor(key, value) {
  if (typeof(value) == "string") {
    return undefined;
  }
  return value;
}

var foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7};
var jsonString = blueConicClient.json.stringify(foo, censor, '...');
alert(jsonString);
//{
//..."week": 45,
//..."month": 7
//}

mail.sendEmail(interactionId, onlyOnce)

Sends an e-mail based on parameter values in the given interaction.

Parameters

Name Data Type Description
interactionId string The id of the interaction sending the mail.
onlyOnce boolean If 'true', the visitor can receive at most one email message for the given interaction.

Returns

Nothing.

Example

var interactionId = '872844e6-e547-43f2-8686-9474cf96db35';
blueConicClient.mail.sendEmail(interactionId, false);

position.subscribe(selector, context, callback)

Subscribes to DOM update events for a specific selector. This function is typically used in Listeners that have rules that should be re-evaluated when a position becomes available. When the selector matches one or more elements the callback function will be called (on the optional context object) once.

Parameters

Name Data Type Description
selector string | string[] The CSS selector to match one or more elements in the page.
context object Context object to call the callback function on. Can be null.
callback function Function that will be called when a DOM update event occurs for one or more elements that match the selector.

Returns

Nothing.

Example

var blueConicClient = new BlueConicClient();

// Subscribe to h1 modification event
blueConicClient.position.subscribe("h1", null, function() {
  // Handle event
});

util.array.ensureArray(obj)

When the given object is not an array a new array is created and the object is added to this array. If the given object is null or undefined an empty array is returned. When the given object is an array it is returned unchanged.

Parameters

Name Data Type Description
obj string The object to convert into an array.

Returns

The given parameter as an array.

Example

var obj = null;
var arr = blueConicClient.util.array.ensureArray(obj);
alert('the array has ' + arr.length + ' items' ); // the array has 0 items

var obj2 = 'test';
var arr2 = blueConicClient.util.array.ensureArray(obj2);
alert('arr2[0] : ' + arr2[0]); // arr2[0] : test

util.array.indexOfArray(array, obj)

Returns the index of the given object in the array. If the object isn't contained in the array, "-1" is returned. If the first parameter isn't an array "-1" is returned.

Note that although most browsers support an indexOf function for arrays you cannot depend on it. For example IE 8 doesn't have an indexOf function for arrays. To be sure that your interaction runs on as many clients as possible you must use util.array.indexOfArray. The util.array.indexOfArray function uses the browser's indexOf when possible

Parameters

Name Data Type Description
array string The array to use.
obj string The object determine the index of.

Returns

Returns the index of the given object in the array. If the object isn't contained in the array, "-1" is returned.
If the first parameter isn't an array, also "-1" is returned.

Example

var arr = ['one', 'two', 'three', 1, 2, 3];

var index = blueConicClient.util.array.indexOfArray(arr, 'one');
alert('index : ' + index); // index : 0

var index = blueConicClient.util.array.indexOfArray(arr, 'six');
alert('index : ' + index); // index : -1

// Note that indexOfArray is case sensitive
var index = blueConicClient.util.array.indexOfArray(arr, 'Two');
alert('index : ' + index); // index : -1

// Note that string '1' is not the same as number 1
var index = blueConicClient.util.array.indexOfArray(arr, '1');
alert('index : ' + index); // index : -1

var index = blueConicClient.util.array.indexOfArray(arr, parseInt('1'));
alert('index : ' + index); // index : 3

util.array.isArray(obj)

Returns true when obj is an array. Returns false in all other cases.

Parameters

Name Data Type Description
obj string The object to check.

Returns

Returns true when the given object is an array. Return false in all other cases.

Example

var isArray = blueConicClient.util.array.isArray(null);
alert('isArray : ' + isArray); // isArray : false

var isArray = blueConicClient.util.array.isArray({"property1" : "one", "property2" : "two"});
alert('isArray : ' + isArray); // isArray : false

var isArray = blueConicClient.util.array.isArray([]);
alert('isArray : ' + isArray); // isArray : true

var isArray = blueConicClient.util.array.isArray(new Array(2));
alert('isArray : ' + isArray); // isArray : true

util.cookie.getCookie(name)

Returns the value of the cookie with the given name or null when the cookie was not found.

Parameters

Name Data Type Description
name string The name of the cookie.

Returns

The value of the cookie.

Example

var value = blueConicClient.util.cookie.getCookie("examplename");

util.cookie.setCookie(name, value)

Sets a cookie on the client with the given name and value. The cookie has an expiration date of one year according to the clock on the client. When the value is null the cookie with the given name is removed. The path of the cookie is "/".

Parameters

Name Data Type Description
name string The name of the cookie.
value string The value of the cookie.

Returns

Nothing.

Example

blueConicClient.util.cookie.setCookie("examplename", "examplevalue");

util.load(library, caller, onSuccess) - deprecated

Loads the specified JavaScript library. If the library name begins with "http", BlueConic retrieves the specified URL.
This method is deprecated:
Please use a library dependency instead or util.loadScript(library, caller, onSuccess).

Parameters

Name Data Type Description
library string The absolute URL of the JavaScript library to load.
caller object Specifies the scope of the onSuccess function.
onSuccess function A function that is called after the library is loaded.

Returns

Nothing.

Example

blueConicClient.util.load("http://code.jquery.com/jquery-1.6.1.min.js", this, function(success) {
  alert('library loaded');
});

util.loadCSS(stylesheet)

Loads a CSS file. Currently there is not a safe way to determine when the CSS is loaded, therefor there is no callback. The URLs are only loaded once.

Parameters

Name Data Type Description
stylesheet string The URL of the stylesheet.

Returns

Nothing.

Example

// Url for this interactiontype
var baseUrl = blueConicClient.getBaseURL(context.getInteractionTypeId());

// Load the css for the fancybox plugin
var fancyboxCSS = baseUrl + 'fancybox/jquery.fancybox.css';
blueConicClient.util.loadCSS(fancyboxCSS);

util.loadScript(library, caller, onSuccess)

Loads a JavaScript library and calls the onSuccess method when it finished. Only absolute URLs are supported. The onSuccess is called without parameters.
The preferred way for loading javascript libraries is using a library dependency.

Parameters

Name Data Type Description
library string The URL of the JavaScript library to load.
caller object Specifies the scope of the onSuccess function.
onSuccess function A function that is called after the library is loaded.

Returns

Nothing.

Example

blueConicClient.util.loadScript("http://code.jquery.com/jquery-1.6.1.min.js", this, function(success) {
  alert('library loaded');
});

util.log(message)

Logs the given message to the console when a console is available. The message is prefixed with "[BC]". Use "<br>" to create newlines.

Parameters

Name Data Type Description
message string The message to log.

Returns

Nothing.

Example

blueConicClient.util.log('Hello world.');

profile.createProfile(caller, onSuccess)

Force creation of a new profile for current user, this profile is created immediately. The current profile is abandoned but not deleted.

Parameters

Name Data Type Description
caller object Specifies the scope of the onSuccess function.
onSuccess function A function that is called after the profile is created.

Returns

Nothing.

Example

jQuery('#create_button').bind('click',function() {
  blueConicClient.profile.createProfile(this, function() {
    console.log('profile created');
  });
});

profile.deleteProfile(caller, onSuccess)

Deletes the profile of the current user. On the next pageview a new profile is created.
Use permission.setLevel(blueConicClient.permission.level.DO_NOT_TRACK) to prevent that a new profile is created the next pageview.

Replaces the deprecated profile.deleteProfile(onSuccess, caller) method (caller must be the first parameter).

Parameters

Name Data Type Description
caller object Specifies the scope of the onSuccess function.
onSuccess function A function that is called after the profile is deleted.

Returns

Nothing.

Example

jQuery('#bc_optout_checkbox').bind('click',function() {
  blueConicClient.profile.deleteProfile();
});

profile.updateProfile(caller, onSuccess)

This function persists updates to a visitor's profile. Note that none of the changes to the profile are persistent until you call blueConicClient.profile.updateProfile().

Parameters

Name Data Type Description
caller object Specifies the scope of the onSuccess function.
onSuccess function A function that is called after the profile is updated.

Returns

Nothing.

Example

// Set and add profile properties
profile.setValues('keywords', ['foo', 'bar']);
profile.addValue('keywords', 'foobar');

// Set permission level
profile.permission.setLevel(blueConicClient.permission.level.ANONYMOUS);

// It is good practice to update multiple mutations at once.
blueConicClient.profile.updateProfile(this, function() {
  // Profile is now persistent
});

InteractionContext Methods

The InteractionContext object holds information about the interaction as it was edited in the Dialogue. The object is injected in the init(blueConicClient, interactionContext) function of a plugin, where it is typically stored in a variable for later use.

var InteractionTypeImpl = InteractionType.extend({

  // Called every time a new interaction of this type is created.
  init: function(blueConicClient, interactionContext) {
    this.blueConicClient = blueConicClient;
    this.interactionContext = interactionContext;
  }
});

getBaseURL()

Returns the base URL for the interactiontype. This can be used to refer to static resources from the interaction type (e.g. images, JavaScript libraries or stylesheets). The base URL is the URL of the interaction type XML definition without the filename. For example, if the URL was 'http://plugins.mysite.com/content/1.0.0/index.xml' then the base URL for the content interaction type is 'http://plugins.mysite.com/content/1.0.0/'. The getBaseURL method returns the URL with the appropriate protocol (http or https). When SSL is required but not available the "http" protocol is used as fallback.

Look at managing plugins for more information.

Parameters

None.

Returns

Returns the base URL (string) of the interactiontype.

Example

In the example below, the file 'logo.gif' is placed on the web server, in the same directory as the interaction type XML definition of the interaction type with the id 'content':

// get an absolute url to a resource from the interactiontype
var baseURL = context.getBaseURL());
var imageLocation = baseURL + 'logo.gif';

getConnection(id)

Returns the connection object that is linked to this interaction as a parameter value. This is useful to retrieve connection parameters in an interaction.

Parameters

Name Data Type Description
id object The identifier of the connection.

Returns

The connection object that is linked to this interaction as a parameter value.

Example

Plugin XML:

  <parameter>
    <id>connectionIds</id>
    <name>
      <label local="en_US">Connections</label>
      <label local="nl_NL">Connecties</label>
    </name>
    <type>connection</type>
  </parameter>

Javascript:

// Retrieve the assigned connectionIds
var connectionIds = this.interactionContext.getParameters()["connectionIds"];

for (var i = 0; i < connectionIds.length; i++) {
  var uuid = connectionIds[i];
  var connection = this.interactionContext.getConnection(uuid);

  // Log the connection parameters
  console.log("connection", connection.getId(), connection.getParameters());
}

getDefaultLocale()

The default locale as configured in BlueConic.

Parameters

None.

Returns

The default locale as configured in BlueConic.

Example

var defaultLocale = this.interactionContext.getDefaultLocale();
alert('defaultLocale : ' + defaultLocale); // defaultLocale : en_US

getDOMElement()

Returns the DOM Element for the current interaction. It uses the interaction's position to retrieve the DOM Element.

Note that the getDOMElement method returns null when the DOM Element was not found. Do not depend on getDOMElement inside the getContent method of your interaction type since we do not guarantee that the DOM is always completely when getContent is called.

Parameters

None.

Returns

Returns the DOM Element for the current interaction.

Example

var domElement = this.interactionContext.getDOMElement();

getInteractionId()

Returns the id of the current interaction. You will need the interactionId to trigger events.

Parameters

None.

Returns

Returns the id of the current interaction.

Example

var interactionId = this.interactionContext.getInteractionId();

getInteractionTypeId()

Returns the id of the interaction type, e.g. "bannerinteractiontype".

Parameters

None.

Returns

Returns the id of the interaction type.

Example

var interactionTypeId = this.interactionContext.getInteractionTypeId();

getLocale()

The locale that was resolved using the setLocaleFunction().

Parameters

None.

Returns

The locale that was resolved using the locale function.

Example

blueConicClient.functions.setLocaleFunction(function(){
  return 'en_US';
});

var locale = this.interactionContext.getLocale();
alert('locale : ' + locale); // locale : en_US

getName()

Returns the name of the current interaction.

Parameters

None.

Returns

Returns the name of the current interaction.

Example

var interactionName = this.interactionContext.getName();

getParameters()

Returns the parameters and their values for the current interaction. The list of parameters is defined by the XML definition file, the values are entered by the marketer on the Interaction tab of a Dialogue. The localeFunction is used to determine for which locale the parameters are returned. When there are no parameters found for this locale then the default locale is used.

Parameters

None.

Returns

Returns an object that contains the parameters and their values as arrays for the current interaction in a specific locale.

Example

Given the following XML definition file exerpt:

  <backend>
    <parameters>
      <parameter>
        <id>url</id>
        <type>string</type>
      </parameter>
      <parameter>
        <id>message</id>
        <type>string</type>
      </parameter>
    </parameters>
  </backend>

This would be the JavaScript to retrieve the parameter values:

// Note: the blueConicClient and interactionContext objects are passed to the InteractionType.init() function.

// Use a simple locale function
this.blueConicClient.functions.setLocaleFunction(function(){
  // Return parameter values for the 'en_US' locale.
  return 'en_US';
});

// Retrieve the parameters
var parameters = this.interactionContext.getParameters();

// Parameter values are returned as an array. However, they might be undefined.
var url = parameters.url ? parameters.url[0] : parameters.url;
var message = parameters.message ? parameters.message[0] : parameters.message;

getPosition()

Returns the position of the current interaction.

Parameters

None.

Returns

Returns the position of the current interaction.

Example

var position = this.interactionContext.getPosition();

getProfile()

Returns the visitor's profile.

Parameters

None.

Returns

Returns a Profile object containing the visitor's profile.

Example

var profile = this.interactionContext.getProfile();

// Set and add profile properties
profile.setValues('keywords', ['foo', 'bar']);
profile.addValue('keywords', 'foobar');

getType()

Returns the type of the interaction, e.g. "LISTENER", "GLOBALLISTENER" or "ACTION".

Parameters

None.

Returns

Returns a string with the type of the interaction.

Example

// Retrieve the type of interaction
var typeName = this.interactionContext.getType();

console.log(typeName);


InteractionType Methods

The InteractionType API contains functions that help you implement your own InteractionType by providing a meaningful context and allowing you to add event handlers. To implement a custom interaction you will need to extend the default BlueConic InteractionType and overrule its default functions usingInteractionType.extend() as follows:

var InteractionTypeImpl = InteractionType.extend({
  init: function(blueConicClient, interactionContext) {
    // ...
  },

  onLoad: function() {
    // ...
  },

  // ...
});

The only parameter to InteractionType.extend() is an object that contains definitions for all API functions that you want to overrule. All available API functions are described below.


getContent()

When implemented this function must return an HTML fragment. BlueConic uses this HTML fragment to update the position configured for the interaction. This function is called by the framework right after the interactions are initialized. The function is useful for updating the content of the interaction's target HTML Element before this element becomes visible. If you define a function getContent(), you should also define the function onLoad().

Implementing the getContent() function has the following restrictions:

  • You cannot use external libraries.
  • You cannot access profile properties.
  • Your implementation must be synchronized.
  • You cannot access the DOM.

These restrictions allow the framework to use the getContent function to update the web page at the earliest stage possible. Consider implementing this function when you need to display content on a web page and you cannot wait until the onLoad() function is called.

Example

var InteractionTypeImpl = InteractionType.extend({
  // ...

  // Display this content as soon as possible
  getContent: function() {
    var loadingDiv = '<div><img src="/loading.gif"/></div>';
    return loadingDiv;
  },

  // ...
});

getPreloadProperties()

This method is used to load one or more properties for the visitor profile. In order to use a profile property you must first load this property. By default BlueConic does not load any of the profile properties. Use the getPreloadProperties to declare for which profile properties BlueConic should preload the values.

You should use preloading instead of profile.loadValues whenever possible. Every call to profile.loadValue results in a new HTTP Request while all preload properties (for all interactions) are retrieved together in one call. This results in better performance because there is only one call to the server in order to retrieve all the properties you need. It is good practice to know which properties you are going to need in your InteractionType implementation and preload them. The loaded profile properties are added to the profile.

Parameters

None.

Returns

An array of strings containing the name of every profile property that you would like to be preloaded.

Example

var InteractionTypeImpl = InteractionType.extend({
  // ...

  // Called to find out which profile properties this plugin needs.
  getPreloadProperties: function() {
    var props = [];
    props.push('visits');
    props.push('visitclicks');
    props.push('keywords');
    return props;
  },

  // ...
});

You can access a preloaded property directly in the onLoad method:

  // Called when an interaction based on this type is executed.
  onLoad: function() {
    var profile = this.blueConicClient.profile.getProfile();
    var keywords = profile.getValues('keywords');
  }

init(blueConicClient, interactionContext)

The init method is the constructor for the InteractionType. Every time a new interaction is created based on your implementation, this method is called to construct a new interaction object.

The init method has two parameters which you might need in your Interaction Type. We recommend that you create a reference to these parameters so that they are accessible throughout your implementation.

Parameters

Name Data Type Description
blueConicClient BlueConicClient A reference to the BlueConicClient Javascript API object that provides access to BlueConic information.
interactionContext InteractionContext A reference to the InteractionContext Javascript API object that provides the context for this interaction.

Returns

Nothing.

Example

var InteractionTypeImpl = InteractionType.extend({
  // ...

  // Called every time a new interaction of this type is created.
  init: function(blueConicClient, interactionContext) {
    // Store the parameters for later use.
    this.blueConicClient = blueConicClient;
    this.interactionContext = null;

    if (typeof interactionContext !== 'undefined') {
      this.interactionContext = interactionContext;
    }
  },

  // ...
});

onLoad()

The function onLoad is where you implement the business logic of your InteractionType This function is called when an interaction based on your interaction type is executed. If you need to call the BlueConicClient API or need the InteractionContext of the interaction, be sure to store a local copy of the references passed to init().

Parameters

None.

Returns

Nothing.

Example

var InteractionTypeImpl = InteractionType.extend({
  // ...

  // Called when an interaction based on this plugin is executed.
  onLoad: function() {
    if (typeof this.interactionContext !== 'undefined' && this.interactionContext !== null) {
      // Get the configured value of the parameter "content" of the dialogue.
      var params = this.interactionContext.getParameters();
      var content = params['content'][0];

      // Get the DOM element indicated by the position of the dialogue.
      var element = this.interactionContext.getDOMElement();

      if (element) {
        element.innerHTML = content;
      }
    }
  },

  // ...
});

onUpdate()

This function will be called when your interaction is being shown in the Simulator and the editor changes any of the parameters of the interaction in the properties widget. It allows you to redraw the interaction based on the changed parameter values.

If you need to call the BlueConicClient API or need the InteractionContext of the interaction, be sure to store a local copy of the references passed toinit().

Parameters

None.

Returns

Nothing.

Example

var InteractionTypeImpl = InteractionType.extend({
  // ...

  // Called when parameters are updated from the backend.
  onUpdate: function() {
    if (typeof this.interactionContext !== 'undefined' && this.interactionContext !== null) {
      // Get the configured value of the parameter "content" of the dialogue.
      var params = this.interactionContext.getParameters();
      var content = params['content'][0];

      // Get the DOM element indicated by the position of the dialogue.
      var element = this.interactionContext.getDOMElement();

      if (element) {
        element.innerHTML = content;
      }
    }
  },

  // ...
});


Profile Methods

The Profile object allows access to profile properties of the current visitor. Values can be read or set, but changes are not persistent until blueConicClient.profile.updateProfile() is called.


addValue(property, value)

Adds a value to the specified property. This value is add to the old values for this property.

Parameters

Name Data Type Description
property string The unique ID of the profile property to which you want to add a value (required).
value string The value to add to the specified property (required).

Returns

Nothing.

Example

var profile = this.interactionContext.getProfile();

profile.setValues("colors", ["blue", "red"]);
profile.addValue("colors", "pink");
// The 'colors' property now contains blue, red and pink.

// Changes are only persistent after calling the updateProfile() method.
this.blueConicClient.profile.updateProfile();

getId()

Returns a BlueConic Profile ID.

Parameters

None.

Returns

The BlueConic profile ID (string) of the current user.

Example

var profileId = profile.getId(); 

permission.getLevel()

Returns the permission level.

Parameters

None.

Returns

The permission level. One of the blueConicClient.permission.level.DO_NOT_TRACK, blueConicClient.permission.level.ANONYMOUS, blueConicClient.permission.level.PERSONAL constants.

Example

profile.permission.getLevel();

getPropertyNames()

Returns an array with the name of the profile properties which are available for the current profile. Note that profile properties which are not loaded are not returned. Look at loadValues to see how to load profile properties.

Use getProfileProperties to retrieve all available profile properties.

Parameters

None.

Returns

Returns an array with profile property names

Example

var profile = this.interactionContext.getProfile();
var propertyNames = profile.getPropertyNames();

for (var i = 0; i < propertyNames.length; i++) {
  var name = propertyNames[i];
  alert(name); // eg: browser
}

getValue(property)

Returns the value (string) for a given property or null if the property was not found or not loaded. When the value is an array then the first element of the array is returned.

Note that BlueConic will not load the values of profile properties by default. It has to be instructed to do so, either by:

  • By defining getPreloadProperties() in your plugin. BlueConic will preload these properties upon initializing the plugin so they are available by the time your frontend code is executed.
  • By calling loadValues() before getValue(). Make sure the values are loaded by calling getValue() from the onSuccess callback function. Avoid using loadValues() and use getPreloadProperties() whenever possible.

Parameters

Name Data Type Description
property string The unique ID of the profile property.

Returns

The value of the given property (string).

Example

var profile = this.interactionContext.getProfile();
var lastvisitdate = profile.getValue('lastvisitdate');

getValues(property)

Returns the values for a given property as an array. When there are no values for the given property, an empty array is returned. When the property leads to a single value then an array with that single value is returned.

Parameters

Name Data Type Description
property string The unique ID of the profile property.

Returns

The values for the given property (array of strings).

Example

var profile = this.interactionContext.getProfile();
var profileKeywords = profile.getValues('keywords');

loadValues(properties, caller, onSuccess)

Loads the given properties for the current profile. The onSuccess function is called after the properties are loaded. The caller object is passed to the onSuccess function.

It is important to realize that loading the values for properties is done asynchronously. This means you can only rely on the values actually being loaded inside the onSuccess function. 

Parameters

Name Data Type Description
properties array of strings An array with the unique IDs of the profile properties that must be loaded.
caller object Specifies the scope of the onSuccess function.
onSuccess function The function to call after the values have been loaded.

Returns

Nothing.

Example

var profile = this.interactionContext.getProfile();
var properties = ['colors', 'websites'];

profile.loadValues(properties, this, function() {
  // Values have been loaded, safe to get now
  var colors = profile.getValue('colors');
  var websites = profile.getValue('websites');
  console.log('colors:', colors);
  console.log('websites:', websites);
});

permission.setLevel(level)

Sets the permission level.

Parameters

Name Data Type Description
level string The level that you want to set. One of the blueConicClient.permission.level.DO_NOT_TRACK, blueConicClient.permission.level.ANONYMOUS, blueConicClient.permission.level.PERSONAL constants.

Returns

Nothing.

Example

var profile = this.interactionContext.getProfile();

// The 'ANONYMOUS' level is set
profile.permission.setLevel(blueConicClient.permission.level.ANONYMOUS);

// Changes are only persistent after calling the updateProfile() method.
this.blueConicClient.profile.updateProfile();

setValue(property, value)

Sets the value of the specified property. Old values are replaced by this value. The changes are not persistent until blueconic.profile.updateProfile is called. The property is created when needed.

Parameters

Name Data Type Description
property string The unique ID of the profile property whose value you want to set (required).
value string The value to assign to the specified property (required).

Returns

Nothing.

Example

var profile = this.interactionContext.getProfile();

profile.setValue("email", "jsmith@blueconic.com");

// Setting a date/time value
profile.setValue("lastvisit", new Date().getTime()); // Changes are only persistent after calling the updateProfile() method. blueConicClient.profile.updateProfile();

setValues(property, values)

Sets the values of the specified property. Old values are replaced by these values. The changes are not persistent until blueConicClient.profile.updateProfile is called. The property is created when needed.

Parameters

Name Data Type Description
property string The unique ID of the profile property whose value you want to set (required).
values array of strings The values to assign to the specified property (required).

Returns

Nothing.

Example

var profile = this.interactionContext.getProfile();

profile.setValues("colors", ["blue", "red"]);

// Changes are only persistent after calling the updateProfile() method.
blueConicClient.profile.updateProfile();

permission.optin.addPlugin(plugin)

Adds a plugin to the opt in list. Plugins in the opt in list are triggered regardless of the permission level.

Parameters

Name Data Type Description
plugin string The plugin that you want to add.

Returns

Nothing.

Example

var profile = this.interactionContext.getProfile();

// The 'myOptInPlugin' plugin is added to the opt in plugins.
profile.permission.optin.addPlugin('myOptInPlugin');

// Changes are only persistent after calling the updateProfile() method.
this.blueConicClient.profile.updateProfile();

permission.optin.addProfileProperty(property)

Adds a profile property to the opt in list. Properties in the opt in list are tracked in the profile regardless of the permission level.

Parameters

Name Data Type Description
property string The unique ID of the profile property that you want to add.

Returns

Nothing.

Example

var profile = this.interactionContext.getProfile();

// The 'myOptInProperty' property is added to the opt in properties.
profile.permission.optin.addProfileProperty('myOptInProperty');

// Changes are only persistent after calling the updateProfile() method.
this.blueConicClient.profile.updateProfile();

permission.optin.getPlugins()

Returns all plugins from the opt in list. Plugins in the opt in list are triggered regardless of the permission level.

Parameters

None.

Returns

An array of plugins.

Example

profile.permission.optin.getPlugins();

permission.optin.getProfileProperties()

Returns all profile properties from the opt in list. Properties in the opt in list are tracked in the profile regardless of the permission level.

Parameters

None.

Returns

An array of profile properties.

Example

var profile = this.interactionContext.getProfile();

profile.permission.optin.getProfileProperties();

permission.optin.removePlugin(plugin)

Removes a plugin from the opt in list. Plugins in the opt in list are triggered regardless of the permission level.

Parameters

Name Data Type Description
plugin string The plugin that you want to remove.

Returns

Nothing.

Example

var profile = this.interactionContext.getProfile();

// The 'myOptInPlugin' plugin is removed to the opt in plugins.
profile.permission.optin.removePlugin('myOptInPlugin');

// Changes are only persistent after calling the updateProfile() method.
this.blueConicClient.profile.updateProfile();

permission.optin.removeProfileProperty(property)

Removes a profile property from the opt in list. Properties in the opt in list are tracked in the profile regardless of the permission level.

Parameters

Name Data Type Description
property string The unique ID of the profile property that you want to remove.

Returns

Nothing.

Example

var profile = this.interactionContext.getProfile();

// The 'myOptInProperty' property is removed to the opt in properties.
profile.permission.optin.removeProfileProperty('myOptInProperty');

// Changes are only persistent after calling the updateProfile() method.
this.blueConicClient.profile.updateProfile();

permission.optout.addPlugin(plugin)

Adds a plugin to the opt out list. Plugins in the opt out list are not triggered regardless of the permission level.

Parameters

Name Data Type Description
plugin string The plugin that you want to add.

Returns

Nothing.

Example

var profile = this.interactionContext.getProfile();

// The 'myOptOutPlugin' plugin is added to the opt out plugins.
profile.permission.optout.addPlugin('myOptOutPlugin');

// Changes are only persistent after calling the updateProfile() method.
this.blueConicClient.profile.updateProfile();

permission.optout.addProfileProperty(property)

Adds a profile property to the opt out list. Properties in the opt out list are not tracked in the profile regardless of the permission level.

Parameters

Name Data Type Description
property string The unique ID of the profile property that you want to add.

Returns

Nothing.

Example

var profile = this.interactionContext.getProfile();

// The 'myOptOutProperty' property is added to the opt out properties.
profile.permission.optout.addProfileProperty('myOptOutProperty');

// Changes are only persistent after calling the updateProfile() method.
this.blueConicClient.profile.updateProfile();

permission.optout.getPlugins()

Returns all plugins from the opt out list. Plugins in the opt out list are not triggered regardless of the permission level.

Parameters

None.

Returns

An array of plugins.

Example

profile.permission.optout.getPlugins();

permission.optout.getProfileProperties()

Returns all profile properties from the opt out list. Properties in the opt out list are not tracked in the profile regardless of the permission level.

Parameters

None.

Returns

An array of profile properties.

Example

var profile = this.interactionContext.getProfile();

profile.permission.optout.getProfileProperties();

permission.optout.removePlugin(plugin)

Removes a plugin from the opt out list. Plugins in the opt out list are not triggered regardless of the permission level.

Parameters

Name Data Type Description
plugin string The plugin that you want to remove.

Returns

Nothing.

Example

var profile = this.interactionContext.getProfile();

// The 'myOptOutPlugin' property is removed to the opt out plugins.
profile.permission.optout.removePlugin('myOptOutPlugin');

// Changes are only persistent after calling the updateProfile() method.
this.blueConicClient.profile.updateProfile();

permission.optout.removeProfileProperty(property)

Removes a profile property from the opt out list. Properties in the opt out list are not tracked in the profile regardless of the permission level.

Parameters

Name Data Type Description
property string The unique ID of the profile property that you want to remove.

Returns

Nothing.

Example

var profile = this.interactionContext.getProfile();

// The 'myOptOutProperty' property is removed to the opt out properties.
profile.permission.optout.removeProfileProperty('myOptOutProperty');

// Changes are only persistent after calling the updateProfile() method.
this.blueConicClient.profile.updateProfile();