Help Center

JavaScript front-end API

The BlueConic JavaScript front-end API is a client-side interface that provides access to BlueConic profiles. It also 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 client-side. It controls the loading of interactions and profiles, and it triggers events. When BlueConic is loaded, an object is injected into the global scope of the browser: window.blueConicClient, and the event onBlueConicLoaded is thrown.

In JavaScript on a webpage, timing is everything. Depending on how the BlueConic tag is placed on the page and where your own JavaScript code runs, BlueConic is either loaded or it isn't, and you will have to account for that in your JavaScript. Once a page view event is published, you can retrieve profile properties and segments for the active user. The code below does this for you:

function doBcApiThings() {
// Do your BlueConic API things here
...
}

// Is BlueConic loaded?
if (typeof window.blueConicClient !== 'undefined' && typeof window.blueConicClient.event !== 'undefined' && typeof window.blueConicClient.event.subscribe !== 'undefined') { // BlueConic is loaded, now we can do API things doBcApiThings(); } else { // Not yet loaded; wait for the "onBlueConicLoaded" event window.addEventListener('onBlueConicLoaded', function () { // BlueConic is loaded, now we can do API things doBcApiThings(); }, false); }


createEvent(eventtype, interactionId, caller, onSuccess)

This method triggers a new event. Events are needed to trigger dialogues and register certain actions of your visitors. For example when a visitor clicks on a banner you want to register this click so BlueConic can track which banners have been clicked.

If your event is only intended to be picked up by listeners (i.e. no dialogues need to be triggered), use event.publish() instead and avoid the overhead of a server call.

Did you check out the Event Trigger listener? Maybe you can simply configure a listener to trigger an event for your dialogues, instead of coding it.

There are three BlueConic-specific events that 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 or dialogue.
  • The VIEW event type can be triggered when an interaction or dialogue is shown to a visitor.
  • The CONVERSION event type is used to register a conversion, for example when the visitor 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. 

The interactiontypes Content Special, Lightbox, Slideout, and Toaster offer the option to enter custom JavaScript. Within that custom JavaScript, the variable blueConicVariantId is made available so for example you can register a conversion for the specific variant you are editing as follows:

if (somethingHappened) {
  blueConicClient.createEvent('CONVERSION', blueConicVariantId);
}

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

doNotShowAgain(dialogueId)

Mark a dialogue and all of its variants to not be shown again to the visitor.

Parameters

Name Data Type Description
dialogueId string The identifier of the dialogue

Returns

Nothing.

Example

var variantId = 'b89e97ee-a4ae-4b0c-9d9e-8d6753c0ba77';

// Find the dialogue of the variant
var dialogueId = blueConicClient.getInteractionNamesById(variantId).dialogueId;

// Don't show the dialogue again
blueConicClient.doNotShowAgain(dialogueId);

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

See 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

var channelId = blueConicClient.getChannelId();


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. For example, "localhost:3737"

Parameters

None.

Returns

Returns the BlueConic hostname.

Example

var hostname = blueConicClient.getHostname();

getInteractionNamesById(variantId)

Returns the dialogue id, dialogue name, variant id, and variant name for the given variant identifier.

Parameters

Name Data Type Description
variantId string The identifier of the variant

Returns

An object containing {dialogueId: "...", name: "...", id: "...", variantName: "..."} or null when not found.

Example

// Get interactions for this page and this profile
var interactions = blueConicClient.getInteractions();

if (interactions.size() > 0) {
  var variantId = interactions[0].id;

  // Display the interaction information
  console.log(blueConicClient.getInteractionNamesById(variantId));
}

getInteractions()

Returns the dialogues and variants that were triggered for the current page view. 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 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 connections 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 "hash change" or "popstate" event. Dialogues that already have been executed will not be executed again, Listeners will be executed again.

Parameters

None.

Returns

Nothing.

Example

// 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 (blueConicClient.isInEditMode()) {
  // The inside of the lightbox is editable
 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 a listening event. The eventContext is an optional array that can be used to pass on parameters to subscribers of the listening event.

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

If you want to trigger dialogues as well, use createEvent() instead.

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 a custom "ON_BANNER_CLICK" listening 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 that will be published using event.publish(eventName, eventContext), for example, BlueConic's own events, or events defined by the Event Trigger listener. When the event is published, the handlerFunction is called with the handlerObject as context. The handlerFunction is called with two arguments:

  • event is the name of the published event. This can be a custom event (for example, 'ON_BANNER_CLICK') or a standard BlueConic event, e.g.:
    • blueConicClient.event.onBeforePreListeners
    • blueConicClient.event.onReady
    • 'PAGEVIEW'
    • blueConicClient.event.onBeforeInteractions
    • blueConicClient.event.onEventReady
  • context an object that 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.

In addition, if event.subscribe is true, then the callback is removed after the event is published the first time after it was registered. (It is false by default.) For instance:

`blueConicClient.event.subscribe("exitintent", {}, () => { console.error("exitintent"); }, true);`

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

/**
  * Subscribe to BlueConic events. You don't have to subscribe to all events
  * as in this example code. Subscribe only to the ones you are interested in. 
  */
var subscribeToBcEvents = function() {
  window.blueConicClient.event.subscribe(window.blueConicClient.event.onBeforePreListeners, 
{}, function() { // BlueConic prelisteners are about to be executed console.log('onBeforePreListeners event'); }); window.blueConicClient.event.subscribe(window.blueConicClient.event.onReady,
{}, function() { // BlueConic is ready console.log('onReady event'); }); window.blueConicClient.event.subscribe('PAGEVIEW', {}, function() { // BlueConic detects a page view console.log('PAGEVIEW event'); }); window.blueConicClient.event.subscribe(window.blueConicClient.event.onBeforeInteractions,
{},function() { // BlueConic interactions are about to be executed console.log('onBeforeInteractions event'); }); window.blueConicClient.event.subscribe(window.blueConicClient.event.onEventReady,
{}, function() { // BlueConic EventReady event was thrown console.log('onEventReady event'); }); }; // Is BlueConic loaded? if (typeof window.blueConicClient != 'undefined' && typeof window.blueConicClient.event != 'undefined' && typeof window.blueConicClient.event.subscribe != "undefined") { // BlueConic is loaded, subscribe to its events subscribeToBcEvents(); } else { // Wait for BlueConic to load window.addEventListener('onBlueConicLoaded', function () { // BlueConic is loaded, subscribe to its events subscribeToBcEvents(); }, false); }
// 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 a localeFunction is the init method of an interaction type. Note that all interactions share the same localeFunction.

See managing languages for more information about configuring languages.

Parameter

Name Data Type Description
localeFunction function A function that 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 be 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 email 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

// 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 some browsers don'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 to 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. 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.');

objective.getObjectives()

Returns all objectives that have the "consent management" flag enabled.

Parameters

Nothing.

Returns

A map (object with objective ID -> Objective) containing all objectives with the "consent management" flag enabled.

Example

// Returns all objectives that have the "consent management" flags enabled
var objectives = blueConicClient.objective.getObjectives();
if (objectives["objective_id"]) {
  // Returns the title of the objective with ID ‘objective_id’
  objectives["objective_id"].getTitle();
} 

objective.getObjectiveById(objectiveId)

Returns one objective with the given ID or null when it cannot be found.

Parameters

Name Data Type Description
objectiveId string The ID of the objective

 

Returns

Returns one Objective with the given ID or null when it cannot be found.

Example

var objective = blueConicClient.objective.getObjectiveById("objective_id"); 
if (objective) { 
// Returns the title of the objective with ID ‘objective_id’ 
objective.getTitle();


// Or combining it with the consented objectives of a profile var profile = blueConicClient.profile.getProfile(); var objectiveIds = profile.getConsentedObjectives(); // loop over the objectives for (var i=0; i < objectives.length; i++){  // retrieve the title of the objectives the profile has consented to var consentedObjective = blueConicClient.objective.getObjectiveById(objectives[i]);   if (consentedObjective) {   
// Returns the title of the consented objective   
consentedObjective.getTitle(); 
} }

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 page view, a new profile is created.
Use permission.setLevel(blueConicClient.permission.level.DO_NOT_TRACK) to prevent that a new profile is created the next page view.

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');

// It is good practice to make multiple modifications and call
// updateProfile() only once (as opposed to calling it every time). blueConicClient.profile.updateProfile(this, function() { // Profile is now persistent });


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 added 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 = blueConicClient.profile.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.
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 that are available for the current profile. Note that profile properties that are not loaded are not returned. See 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 = blueConicClient.profile.getProfile(); 
var propertyNames = profile.getPropertyNames();

for (var i = 0; i < propertyNames.length; i++) {
  var name = propertyNames[i];
  alert(name); // e.g.: 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:

  • 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.
  • Calling loadValues() before getValue(). Make sure the values are loaded by calling getValue() from the onSuccess callback function. Note: Avoid using loadValues() in plugins, and use getPreloadProperties() where 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 = blueConicClient.profile.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 = blueConicClient.profile.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 = blueConicClient.profile.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 = blueConicClient.profile.getProfile(); 

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

// Changes are only persistent after calling the updateProfile() method.
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 = blueConicClient.profile.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 = blueConicClient.profile.getProfile(); 

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

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


incrementValue(property, value)

Increments a single property value to the profile.

Parameters

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

Returns

Nothing.

Example

var profile = blueConicClient.profile.getProfile(); 

profile.incrementValue("purchases", "1");

 // Increment "1" to the values for the "purchases" profile property

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 you want to add

Returns

Nothing.

Example

var profile = blueConicClient.profile.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.
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 you want to add

Returns

Nothing.

Example

var profile = blueConicClient.profile.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.
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 = blueConicClient.profile.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 you want to remove

Returns

Nothing.

Example

var profile = blueConicClient.profile.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.
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 you want to remove

Returns

Nothing.

Example

var profile = blueConicClient.profile.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.
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 you want to add

Returns

Nothing.

Example

var profile = blueConicClient.profile.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. 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 you want to add

Returns

Nothing.

Example

var profile = blueConicClient.profile.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.
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 = blueConicClient.profile.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 you want to remove

Returns

Nothing.

Example

var profile = blueConicClient.profile.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.
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 you want to remove

Returns

Nothing.

Example

var profile = blueConicClient.profile.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.
blueConicClient.profile.updateProfile();

recommendation.getRecommendations(requestParameters, callback)

Returns the recommendations for the given parameters.

Parameters

  • requestParameters (Object) - The object containing the parameters for the recommendations, which are translated into url-encoded querystring parameters.
Name Type Description
profileId String Optional. The profile ID to get the recommendations for.
Note that the profile ID is required when you use a recommendation algorithm that depends on the profile, such as 'Collaborative filtering' or 'Seen articles / Seen products'.
storeId String Required. The store ID to retrieve the recommendation items from.
itemId String Optional. The id of the current item. If undefined, the referrer is used to determine the current itemId.
request Object[]

An array of objects representing the recommendation 'sets' that are requested.

Each set can have the following properties:

  • id - Internal string to identify the recommendation set.
  • boosts - Array of boost expressions, as described in the boosts section below.
  • filters - Array of filter expressions, as described in the filters section below.
  • count - The number of items this set should contain. When undefined, this set will contain default fallback items to fill the "empty spaces" that other sets could not fill themselves.

Default fallback items: You can define a default recommendations set to fall back to when not enough matching recommendations can be found. Avoid using the count setting for the “default” algorithm set, because the count will automatically be determined based how many recommendations are still missing. The “default” algorithm set will only be used if the "count" property is not set and if the other algorithm sets are not able to supply enough recommendations.

Example:

[{
  "id": "first",
  "boosts": [{
    "value": "1",
    "algorithm": "RECENCY"
  }],
  "filters": [],
  "count": 2
}, {
  "id": "second",
  "boosts": [{
    "value": "2",
    "algorithm": "CATEGORY"
  }],
  "filters": [],
  "count": 2
}, {
  "id": "third",
  "boosts": [{
    "value": "3",
    "algorithm": "RECENCY"
  }],
  "count": 2
}, {  
"id": "default", 
"boosts": [{   
"value": "1",   
"algorithm": "RECENT_CTR"  }]
}
frequencyCap number Optional. Maximum number of times to show a recommendation per item.
imageWidth String Optional. The width of the recommendation images to return.
imageHeight String Optional. The height of the recommendation images to return.
    • Boosts
Name Type Description
boosts Object[]

An array of objects representing the boost on algorithms. The items in the array must have a value property, which can be a number between 1 and 10 (included). The algorithm property must be one of:

  • RECENT_VIEW (Breaking news)
  • RECENT_ENTRYPAGE (Viral news)
  • RECENT_CTR (Recent high CTRs)
  • SAME_CATEGORY (Same category)
  • LOOK_ALIKE (Look-alike-articles)
  • RECENCY (Recency)
  • INTEREST (Same interest)
  • COLLABORATIVE_FILTERING (Collaborative filtering)
  • RECENTLY_VIEWED (Seen articles)

When using COLLABORATIVE_FILTERING or INTEREST, an optional rampUp property can be specified with the value FAST or SLOW.

Example:

[{
  "value": "3",
  "algorithm": "RECENCY"
}, {
  "value": "1",
  "algorithm": "CATEGORY"
}]
            

 

    • Filters
Name Type Description
filters Object[]

An array of strings representing the filters on recommendation items.

Example:

[
  "hasproperty:url",
  "!hasproperty:description",
  "category:a,b,c",
  "!category:d,e,f",
  "category:x", !"category:y",
  "publicationDate>2023-06-01T00:00+0200"
]

The example above shows the power of expression available:

  • hasproperty:url - Metadata field "url" must contain a value.
  • !hasproperty:description - Metadata field "description" must not contain a value.
  • category:a,b,c - Metadata field "category" must match any of the given values "a", "b", or "c".
  • !category:d,e,f - Metadata field "category" must not match any of the given values "d", "e", or "f".
  • category:x - Metadata field "category" must match with value "x".
  • !category:y - Metadata field "category" must not match with value "y".
  • publicationDate>2023-06-01T00:00+0200 - Metadata field "publicationDate" must have a value later than the given date. Valid operators: <, >, <=, and >=
  • ! - Invert a given filter (NOT).

The relation between the filters is AND.

In addition to the generic expressions shown above, the following precompiled values can be used:

  • VIEWED - Exclude items that were viewed.
  • SHOPPINGCART - Exclude items that are in the shoppingcart.
  • BOUGHT - Exclude items that were bought.
  • VIEWED ONLY - Include view items only.
  • SHOPPINGCART_ONLY - Include items that are in the shopping cart only.
  • BOUGHT_ONLY - Only include items that are already bought.
  • SAME_CATEGORY - Only include items of the same category.
  • IN_STOCK - Only include items that are in stock.

 

  • callback (function) - The callback function that is called when the recommendations are returned. The callback will receive a response object containing the recommended items and their metadata. The response object provides two functions that are useful in getting the recommended items:
Function Description
getItems() Returns an array of recommendation item objects for all requested sets combined.
getGroupedItems() Returns a map of recommendation items grouped per requested set.

The response object can be used with a callback function like below:

function handleRecommendations(response) { 
// Get the recommendation items
var items = response.getItems();

console.log(items);
}

A single recommendation item object will look something like this:

{ 
"score": ["0.42093023255813954"],
"image": ["INSERT URL HERE"],
"name": ["News Article"],
"description": ["Lorem ipsum dolor sic amet ..."],
"ID": ["https://www.yoursite.com/article.html"],
"recommendationId": ["fead3401-1adb-41f9-b198-1c123abdeffe"],
"category": ["news"],
"URL": ["https://www.yoursite.com/article.html"]
}

The fields returned depend on what metadata is configured in the Content Collector. E.g.:

Name Type Description

score

String[] Score of the item based on the parameters presented to the recommendations engine. Value between 0 (irrelevant) and 1 (very relevant).

image

String[] URL of the item's image.
name String[] Name of the item.
description String[] Description of the item.
ID String[] ID of the item.
recommendationId String[] BlueConic UUID of the item.
category String[] Categories of the item.
URL String[] Links to the item.

Returns

Nothing. Results are returned as the response parameter to the callback function.

Example

// Callback function for recommendations
function doSomething(response) {
  // Get the recommendation items
  var items = response.getItems();

  // Do something with the recommended items
  console.log(items);
}

// Contact us for your contentStore id
var storeId = "065f32b1-cda5-48dd-9e69-3339cc20e498";
var profileId = blueConicClient.profile.getProfile().getId();
var itemId = document.location.hostname + document.location.pathname;

// Get recommendations
blueConicClient.recommendation.getRecommendations({
  profileId: profileId,
  storeId: storeId,
  itemId: itemId,

  // Request three sets of recommendations. The first set returns a
  // maximum of 4 of the most recent news articles, the second set returns
  // a maximum of 6 of articles in the same category, and the final set
  // acts as a default set of recent articles in case any of the previous
  // sets didn't reach their maximum of recommendations.
  request: [{
    id: "first",
    boosts: [{
      value: 1,
      algorithm: "RECENCY"
    }],
    filters: ["category:news"],
    count: 4
  }, {
    id: "second",
    boosts: [{
      value: 2,
      algorithm: "CATEGORY"
    }],
    filters: [],
    count: 6
  }, {
    id: "default",
    boosts: [{
      value: 3,
      algorithm: "RECENCY"
    }]
  }],
  frequencyCap: 1000
}, doSomething);

getPrivacyLegislation()

Returns the privacy legislation determined for this profile (based on IP address).

Parameters

Nothing.

Returns

Returns a string representing the privacy legislation.

Example

var profile = blueConicClient.profile.getProfile(); 
profile.getPrivacyLegislation();

setPrivacyLegislation(legislation)

Set the privacy legislation for this profile.

Parameters

Name Data Type Description
legislation string The privacy legislation

Returns

Nothing.

Example

var profile = blueConicClient.profile.getProfile(); 
profile.setPrivacyLegislation(‘GDPR’);
blueConicClient.profile.updateProfile(this, function() {  
// Privacy legislation is now updated
});

getConsentedObjectives()

Returns the objective IDs for which the profile has given explicit consent.

Parameters

Nothing.

Returns

An array of objective IDs for which the user has given explicit consent.

Example

var profile = blueConicClient.profile.getProfile(); 
var objectiveIds = profile.getConsentedObjectives();

getRefusedObjectives()

Returns the objective IDs for which the profile has explicitly refused consent.

Parameters

Nothing.

Returns

An array of objective IDs for which the user has explicitly refused consent.

Example

var profile = blueConicClient.profile.getProfile(); 
var objectiveIds = profile.getRefusedObjectives();

addConsentedObjective(objectiveId)

Adds an objective to the list of consented objectives. The changes are not persistent until blueConicClient.profile.updateProfile is called.

Parameters

Name

Data Type

Description

objectiveId

string

The unique ID of the objective that is consented to (required)

Returns

Nothing.

Example

var profile = blueConicClient.profile.getProfile(); 
profile.addConsentedObjective("objective_id");  // Changes are only persistent after calling the updateProfile() method.
blueConicClient.profile.updateProfile();

setConsentedObjectives(objectiveId)

Sets the consented objectives of the profile. Old values are replaced by these values. The changes are not persistent until blueConicClient.profile.updateProfile is called.

Parameters

Name

Data Type

Description

objectiveIds

Array of strings

The unique IDs of the objectives that have been consented to (required).

Returns

Nothing.

Example

var profile = blueConicClient.profile.getProfile(); 
profile.setConsentedObjectives(["objective_id_1", "objective_id_2"]);
// Changes are only persistent after calling the updateProfile() method.
blueConicClient.profile.updateProfile();

addRefusedObjective(objectiveId)

Adds an objective to the list of refused objectives. The changes are not persistent until blueConicClient.profile.updateProfile is called.

Parameters

Name

Data Type

Description

objectiveId

string

The unique ID of the objective that is refused (required).

Returns

Nothing.

Example

var profile = blueConicClient.profile.getProfile(); 
profile.addRefusedObjective("objective_id");
// Changes are only persistent after calling the updateProfile() method.
blueConicClient.profile.updateProfile();

setRefusedObjectives(objectiveIds)

Sets the refused objectives of the profile. Old values are replaced by these values. The changes are not persistent until blueConicClient.profile.updateProfile is called.

Parameters

Name

Data Type

Description

objectiveIds

Array of strings

The unique IDs of the objectives that are refused (required).

Returns

Nothing.

Example

var profile = blueConicClient.profile.getProfile(); 
profile.setRefusedObjectives(["objective_id_1", "objective_id_2"]);
// Changes are only persistent after calling the updateProfile() method.
blueConicClient.profile.updateProfile();

timeline.createEvent(eventType, eventDate, eventAttributes, caller, onSuccess)

Create an event on the timeline of the profile. Note that when using this method, the ID of the timeline event will be an automatically generated UUID.

Parameters

Name Data Type Description
eventType string The type of the Timeline event
eventDate date Date associated with the Timeline event
eventAttributes object Attributes for the Timeline 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

blueConicClient.profile.getProfile().timeline.createEvent("MY_VIEW", new Date(), 
{myText:"mytext", orderlines: [{subText: "123"},
{subText: "345", subDate: new Date()}]}, this, function(){ console.error(arguments); })

timeline.createEventById(eventId, eventType, eventDate, eventAttributes, caller, onSuccess)

Create an event on the timeline of the profile. This method allows you to explicitly specify the event identifier.

Parameters

Name Data Type Description
eventID string The ID of the Timeline event
eventType string The type of the Timeline event
eventDate date Date associated with the Timeline event
eventAttributes object Attributes for the Timeline 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

blueConicClient.profile.getProfile().timeline.createEventById("MY_ID", 
"MY_VIEW", new Date(), {myText:"mytext", orderlines: [{subText: "123"},
{subText: "345", subDate: new Date()}]}, this, function(){ console.error(arguments); })

getLifecycleStages()

Returns all BlueConic lifecycle stages that the Profile belongs to.

Parameters

None.

Returns

An array of BlueConic LifecycleStage objects that the profile of the current user belongs to. LifecycleStage objects provide functions to retrieve lifecycle and stage ID and name information.

Function Description
getLifecycle() Returns an object with functions getId() and getName() to identify the lifecycle.
getStage() Returns an object with functions getId() and getName() to identify the stage of the lifecycle.

Example

var profile = blueConicClient.profile.getProfile();
 
// Process all lifecycle stages 
profile.getLifecycleStages().forEach(lifecycleStage => {
    // Lifecycle information
    const lifecycleName = lifecycleStage.getLifecycle().getName();
    const lifecycleId = lifecycleStage.getLifecycle().getId();
 
    // Stage information
    const stageName = lifecycleStage.getStage().getName();
    const stageId = lifecycleStage.getStage().getId();
 
    console.log(`Profile is part of stage "${stageName}" (ID: "${stageId}") 
in lifecycle "${lifecycleName}" (ID: "${lifecycleId}")`); });

Objectives Methods

The Objective object holds information about the objective as it created in the BlueConic UI. This object is returned when using blueConicClient.objective.getObjectives() or blueConicClient.objective.getObjectiveById().

// Returns all objectives that have the "consent management" flags enabled
var objectives = blueConicClient.objective.getObjectives();
// Return one specific objective or null when it cannot be found
var objective = blueConicClient.objective.getObjectiveById("objective_id");

getId()

Returns the ID of the objective. This ID can be used for managing consent for a profile, through the "setConsentedObjectives()", "addConsentedObjective()", setRefusedObjectives()" and "addRefusedObjective()" profile methods

Parameters

None.

Returns

Returns the ID of the objective.

Example 

// Return one specific objective or null when it cannot be found
var objective = blueConicClient.objective.getObjectiveById("objective_id"); if (objective) {
// Return the ID of the objective
var id = objective.getId();
}
 

getTitle()

Returns the title of the objective, as entered in the "title" field of an objective.

Parameters

None.

Returns

Returns the title of the objective.

Example 

// Return one specific objective or null when it cannot be found
var objective = blueConicClient.objective.getObjectiveById("objective_id"); if (objective) {
// Return the title of the objective
var title = objective.getTitle();
}


getDescription()

Returns the description of the objective, as entered in the "description" field of an objective.

Parameters

None.

Returns

Returns the description of the objective.

Example 

// Return one specific objective or null when it cannot be found
var objective = blueConicClient.objective.getObjectiveById("objective_id"); if (objective) {
// Return the description of the objective
var description = objective.getDescription();
}

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.

See 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 excerpt:

  <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 that you might need in your Interaction Type. We recommend that you create a reference to these parameters so 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 to init().

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; } } }, // ... });
Was this article helpful?
0 out of 0 found this helpful