Logo

JavaScript

JavaScript #

This document describes the integration strategy for JavaScript.

This strategy is recommended when integrating web applications, both desktop and mobile, and also for mobile applications created using JavaScript frameworks such as Cordova.

Using this SDK, no extra integration mechanism nor web services integration is needed.

Library installation #

To start using the library in a web environment, insert the following code snippet inside the HTML <body> tag:

<script type='text/javascript' src='http://SERVER:PORT/sdk/javascript/prisma.js'></script>
<script type = "text/javascript" >
    prisma.load(SERVER, PORT, APP_TOKEN, CUSTOMER_ID, integrations, protocol, options);
</script>

Be sure to replace the variables SERVER, PORT, APP_TOKEN and CUSTOMER_ID to match your installation parameters.

To obtain the parameters server, port and app_token please refer to the Settings/Applications section in the administration console.

Choosing the channel to integrate in this screen, it’s possible to display the code snippet with the needed values.

Remember that setting the parameter customer_id and the placeholders vector is responsibility of the integration team.

Note: This code will load the library asynchrounously, so the site will load quickly even with this dependency.

Parametrization #

load(server, port, app_token, customer_id, placeholders_vector)
ParameterData typeRequired?Description
serverstringyesServer address where campaign platform is located.
portstringyesAccess port where the campaign platform is located.
app_tokenstringyesApplication token of the application being integrated.
customer_idstringyesCustomer identifier, if available.
integrationsvectoryesVector with the list of placeholders to integrate in the current page.
protocolstringno“http:” or “https:” depending on the availability of SSL access.
optionsstringnoOptional configuration parameters, callbacks and other elements.

Placeholders to integrate #

The integration vector in the load function, describes the different placeholders to integrate in the page with the integration snippet.

The allowed keys for each vector are listed in the following table:

KeyData TypeRequired?Description
placeholderIdstringyesPlaceholder identifier as created in the campaign’s platform.
elemendIdstringyesHTML element identifier where the placeholder banners will be created.
unrolledbooleannoWhen the placeholder supports more than one campaign, this flags indicates whether to display the banners unrolled or not. Meaning that the qualifying campaigns for the placeholder will be shown simultaneously and not in carousel mode. This value defaults to false
fallbackUrlstringnoFully qualified url of the image to use in this placeholder if the platform is not available.
contextObjectnoContext values for this placeholder, useful to select campaigns filtering against this context values.
isolatedbooleannoWhen using HTML banners with a style that can be affected by the main site, this flag forces the banner to be loaded in an isolated iframe. Default value is true.

In the following example, a parametrized initialization is done for three different placeholders in the same page.

<script type='text/javascript'>
   prisma.load('localhost', '443', '8e2626da-4ee1-45c7-b269-50df530dbc6e',
      "137-W", [{placeholderId : "MainHomeBanner",
                 elementId : "banner_flash",},
                {placeholderId: "RightHomeBanner",
                 elementId: "banner_right"},
                {placeholderId : "LeftHomeBanner",
                 elementId : "banner_left"}],
                 "https:");
 </script>

In this other example, only one placeholder is integrated in unrolled mode, and with a filtering context.

<script type='text/javascript'>
   prisma.load('localhost', '443', '8e2626da-4ee1-45c7-b269-50df530dbc6e',
      "137-W", [{placeholderId : "PromocionesHome",
                       context : {"productId" : "1234"},
                 unrolled : true,
                 elementId : "promo_list",}
                 "https:");
 </script>

Note: In the examples the fixed value 137-W is used as customer identifier. In practice, this value must be set dinamically according to the authenticated customer when programming the integration.

Optional Parameters #

It is possible to provide a parameter with different options for integration. The list of properties is detailed below:

KeyData TypeRequired?Description
onLoadedfunctionnoCallback, it will be called once initialization is complete See more details
onLoadFailedfunctionnoCallback, it will be called if there is an error in the initialization. See more details
onRedirectfunctionnoCallback, it will be called in case there is a redirect in the conversion funnel. See more details
onPopupfunctionnoCallback, allows you to control the deployment of popups. See more details
storageTypestringnoDetermine what type of storage will be used to store browsing information, options: "local", "cookies". If you do not provide a value, cookies will be used
reloadPopupsOnResetbooleannoDetermines if the popups will be shown again once the integration is reloaded (with a conversion for example). The default value is: false
languagestringnoDetermines the language to be used for the internationalization of texts in integration. The default value is: es
useTranslatorbooleannoIt determines if the internationalization of the texts will be carried out in the integration. The default value is: true
channelstringnoDetermines the channel that is being integrated. Available values ​​are: web, mobile, mail, facebook, twitter, atm, referral,business-event and sms. The default value is: web
platformstringnoDetermines the platform the integration is running on. The default is the name of the browser. (ex: chrome,firefox, etc)

OnLoaded Callback #

The onLoaded callback from the SDK can be implemented in case there is a need to control when the integration loading is completed.

It may be set up as follows:

<div id="container"></div>

<script type='text/javascript'>
var onLoaded = function(banners) {
    console.log("Successfully loaded Prisma Campaigns");
};

prisma.load(
    'campaigns.bank.com',
    '80',
    '8e2626da-4ee1-45c7-b269-50df530dbc6e',
    '137-W',
    [{'placeholderId': 'MainBanner', 'elementId': 'container'}],
    'http:',
    {onLoaded: onLoaded}
);
</script>

The options parameter in the load method needs to include a callback named onLoaded. The platform will invoke this function once the integration has successfully finished loading.

The onLoadedcallback will receive the banners that match each customer as a parameter.

OnLoadFailed Callback #

In case the user needs to handle any errors while loading the integration, they can implement the onLoadFailed callback that is included in the SDK.

The setup is as follows:

<div id="container"></div>

<script type='text/javascript'>
var onLoadFailed = function(error) {
    console.log("There has been an error initializing the integration with Prisma Campaigns");
};

prisma.load(
    'campaigns.bank.com',
    '80',
    '8e2626da-4ee1-45c7-b269-50df530dbc6e',
    '137-W',
    [{'placeholderId': 'MainBanner', 'elementId': 'container'}],
    'http:',
    {onLoadFailed: onLoadFailed}
);
</script>

The options parameter in the load method from the SDK needs to include an onLoadedFailed callback, that will be invoked by the platform if there has been an error loading the integration.

The onLoadedcallback, if desired, will receive information about the loading error using the following attributes:

KeyData TypeOptional Y/NDescription
DataStringNoThe placeholder identifier as configured in the campaign platform.
StatusStringNoHTML identifier where the banners for the placeholder will be loaded.

OnRedirect Callback #

The SDK provides a callback named onRedirect to redirect users to a site as part of a conversion funnel step.

The setup should be as follows:

<div id="container"></div>

<script type='text/javascript'>
var onRedirect = function(url) {
    console.log("You will be redirected to the website" + url);
};

prisma.load(
    'campaigns.bank.com',
    '80', '8e2626da-4ee1-45c7-b269-50df530dbc6e',
    '137-W',
    [{'placeholderId': 'MainBanner', 'elementId': 'container'}],
    'http:',
    {onRedirect: onRedirect}
);
</script>

The options parameter in the SDK load method requires an onRedirect callback that will be invoked by the tool when a redirect step is executed.

The onRedirect callback will receive the URL configured as a parameter.

Examples #

For the following examples these configuration parameters are used:

ParameterValue
servercampaigns.bank.com
port80
app_token175b18e2-08f2-43c2-953a-91f370a0fe23

Public access, unidentified #

The following sample shows a public web site with the customer not identified, with only one placeholder integrated.

In this case the placeholder identified in the system is Portal - Main Banner and the html node to display the image has as id mainbanner.

<script type='text/javascript' src='http://campaigns.bank.com:80/sdk/javascript/prisma.js'></script>
<script type = "text/javascript" >
      prisma.load("campaigns.bank.com", "80",
            "175b18e2-08f2-43c2-953a-91f370a0fe23",
            "",
            [{placeholderId : "Portal - Main Banner",
              elementId : "mainbanner",}]);
</script>

When the customer is not identified, the parameter customer_id must be sent empty.

For the mainbanner html tag, there’s no restriction on the type of element to use, tipically these will be div elements.

<div id="mainbanner"></div>

Identified access #

When the person navigating the web site is an identified customer, the customer_id parameter of the load function must be used.

<script type='text/javascript' src='http://campaigns.bank.com:80/sdk/javascript/prisma.js'></script>
<script type = "text/javascript" >
    prisma.load("campaigns.bank.com", "80",
          "175b18e2-08f2-43c2-953a-91f370a0fe23",
           session.customer_id,
          [{placeholderId : "Position - Left",
            elementId : "left_banner"}
{placeholderId : "Position - Right",
            elementId : "right_banner"}]);
</script>

In this case, it’s assumed the customer identifier to use is defined in the variable session.customer_id. Also in this case, two placeholders are used to load images:

<div id="left_banner"></div>
<div id="right_banner"></div>

Campaign list #

When a banner placeholder isn’t used, it’s possible to obtain all the active campaigns for a given customer.

activeCampaigns(customerId, category, group, fnResults)
ParameterData TypeRequired?Description
customerIdstringYesCustomer identifier to retrieve qualifying campaigns for, when searching for unidentified campaigns the empty string must be used “”.
categorystringNoCampaign category to search campaigns for, optional parameter to be used as filter.
groupstringNoCampaign group to search campaigns for, optional parameter to be used as filter.
fnResultsfunctionNoFunction to be called async when results are obtained.

This function must be called after the library initialization was completed, using the load function as described in the previous sections.

The fnResults function receives the campaign list, with the following information: name, category, group, customOffer y funnelUrl.

prisma.client.activeCampaigns("137-W", "Sales","Mortgages",
    function (campaigns) {
        for (var i = 0 ; i < campaigns.length; i++) {
            console.log(campaigns[i].name);
        }
    });

It’s also possible to start the conversion funnel for one of the found campaigns, using the startFunnel function, which starts the conversion process in a new window.

In the following example all mortgage sale campaigns are retrieved, and for the most important with the loanRate parameter set, conversion funnel is started.

prisma.client.activeCampaigns("137-W", "Sales","Mortgages",
             function (campaigns) {
               for (var i = 0 ; i < campaigns.length; i++) {
                    if (campaigns[i].customOffer.loanRate != undefined) {
                        campaigns[i].startFunnel();
                    break;
                       }
                  }
             });

Personalized carousel #

When banners are to be created using a custom control or component, the onLoaded event must be used.

There are two important things to consider for this behavior:

  1. The elementId parameter with the location to create the banner must be set to null.
  2. The onLoaded function will receive the retrieved banners.

The received banner list is a dictionary, with each key being the placeholder identifier.

Also, each returned value contains a list of available banners, when more than one campaign matches for the placeholder. This list is found in the images attribute of each banner.

Then, using the show method it’s possible to append the banner or image to any element of the page.

In this sample, a new element called my-parent is created on the page, with all the images or html banners received for the placeholder called “MainBanner”.

<div id="my-parent"></div>

<script type='text/javascript'>
var onLoaded = function(banners) {
    var carouselParent = document.getElementById("my-parent");
    var prisma = this;
          var banner = banners["MainBanner"];
          for (var i = 0; i < banner.images.length; i++) {
              var image = banner.images[i];
              image.show(carouselParent);
          }
};

prisma.load('campaigns.bank.com', '80', '8e2626da-4ee1-45c7-b269-50df530dbc6e',
"137-W", [{"placeholderId" : "MainBanner",
                      "elementId" : null},],
           "http:", {onLoaded : onLoaded});
</script>

Personalized popups #

If the popup displayed is to be controlled from the application, this is possible using the onPopup callback from the SDK.

Callback must be used as follows:

<div id="my-parent"></div>

<script type='text/javascript'>
var onPopup = function(popup) {
    if (popup.banner.category == "Sales") {
        //display a personalized popup
        //return true to indicate
        //popup was resolved personalized
        return true;
    }
};

prisma.load('campaigns.bank.com', '80', '8e2626da-4ee1-45c7-b269-50df530dbc6e',
"137-W", [{"placeholderId" : "MainBanner",
                      "elementId" : null},],
           "http:", {onPopup : onPopup});
      </script>

Using the options parameter of the load method, the onPopup callback must be set. This callback will be called by the platform when among the qualifying campaigns for the customer, one of them is displaying a popup.

The onPopup callback receives as parameter the popup to display, with the following attributes:

onPopup(popup)
ParameterData typeRequired?Description
widthlongYesWidth of the configured placeholder.
heightstringYesHeight of the configured placeholder.
bannerBannerYesBanner configuration to display as popup.
hideClosebooleanYesWhether to hide or not the close button for the popup.
dismissFnfunctionNoWhen the campaign for the popup allows for dismissal, this is the function to call to do the corresponding dismiss.

The banner parameter has different attributes if it’s an image or html banner. This allows, using the referenced content, to use it to display the popup in a customized way according to the requirements of the application.

BannerHTML()
ParameterData typeRequired?Description
widthlongYesWidth of the configured placeholder.
heightstringYesHeight of the configured placeholder.
categorystringYesCategory name of the campaign for this banner.
groupstringYesGroup name of the campaign for this banner.
FunnelfunnelYesCampaign funnel configuration
isolatedbooleanYesWhether to show the popup in isolated mode.
contentstringYesHTML content of the banner to be displayed
BannerImage()
ParameterData typeRequired?Description
widthlongYesWidth of the configured placeholder.
heightstringYesHeight of the configured placeholder.
categorystringYesCategory name of the campaign for this banner.
groupstringYesGroup name of the campaign for this banner.
FunnelfunnelYesCampaign funnel configuration
linkstringYesImage link to display.

Conversion #

Mark a customer as converted in a campaign.

<script type='text/javascript' src='http://SERVER:PORT/sdk/javascript/prisma.js'></script>
<script type = "text/javascript" >
    prisma.convert(server, port, app_token, protocol, campaignId)
</script>
ParameterData typeRequired?Description
serverstringyesServer address where campaign platform is located.
portstringyesAccess port where the campaign platform is located.
app_tokenstringyesApplication token of the application being integrated.
protocolstringYes“http:” o “https:” if SSL access is available or not.
campaignIdstringYesCampaign identifier.
callbackfunctionnoFunction to execute once the conversion finishes. It must receive a parameter, which will be the api response.

The campaignId parameter is obtained from the URL used in the redirect.

The following steps must be taken:

  • Create a redirect step in the campaign funnel to your application.
  • The redirect has 3 parameters in the query string: campaign-id, trail-id and tracking-token.

These parameters can be obtained from the backend or using JavaScript inside the browser with the following function:

<script type = "text/javascript" >
    function getParameterByName(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    }
</script>

Cordova #

In order to display HTML banners in an app built on Cordova, you need to either:

  • Set isolated = false for the placeholder, so the banner isn’t created inside an iframe (see Placeholders to integrate).
  • Add the rule <allow-navigation href="about:" /> or <allow-navigation href="*" /> to Cordova’s config.xml, so the banner’s iframe is loaded.