# Deployment Files and Resources

Download latest RpiWebClient files and view RedPoint Realtime API swagger page

# RedPoint JavaScript Web Client

The RpiWebClient class represents the RPI Realtime application on the client-side and is loaded into a web page by including rpiWebClient-6.4.js into the page. When RpiWebClient is loaded, an object is injected into the global scope of the browser: window.rpiWebClient, and the event rpiWebClientLoad is raised.

The web client provides methods to enable developers to:

- Register the page visitor with RPI Realtime
- Send additional Realtime Parameters to the RPI Realtime Visitor Cache
- Send custom events to RPI Realtime Web Events
- Get/render RPI context decisions
- Get/render RPI Smart Asset decisions

It is recommended that the rpiWebClient-6.4.js file be loaded as close to the top of the web page as possible (ie. in the <HEAD> tag). Since it's typical for RPI Realtime Decisions to replace page DOM elements with their results, any code that references RPIWebClient should be defined as close to the bottom of the web page as possible (ie. after the </BODY> close tag).

With JavaScript on a web page, load order is critically important. In cases where rpiWebClient-6.4.js needs to be loaded after the JavaScript code that references it is defined, listening for the rpiWebClientLoad event will ensure that the JavaScript code only executes after RpiWebClient is loaded.

### Example

    if (window.rpiWebClient) { // check if RpiWebClient is already loaded
       doSomethingWithRpiWebClient();
    }
    else { // set an event listener if RpiWebClient hasn't been loaded
       window.addEventListener("rpiWebClientLoad", function(event) {
           doSomethingWithRpiWebClient();
       });
    }

    function doSomethingWithRpiWebClient() {
       rpiWebClient.init( {...} )
    }

## Initializing RedPoint Web Client

Initializing the web client will register the page visitor with RPI Realtime and submit a pageVisit event to RPI Realtime Web Events. When RpiWebClient is initialized, the rpiWebClientInit event is raised.

The web client is initialized by calling rpiWebClient.init(). The init method accepts the following optional parameters:

- opts- RpiWebClientConfig object defining the web client configuration options
- callback- Javascript function to execute after initialization

NOTE: using the callback ensures that the RPI Realtime visitor id is set prior to executing any additional logic.

### Example

    rpiWebClient.init({
        debug: true,
        clientId: "11111111-1111-1111-1111-111111111111",
        serverUrl: "rpirealtime.example.net",
        enableClickTracking: false,
        enablePageVisitTracking: false,
        visitorCookieDuration: 365,
        realtimeCookieDomain: ".example.net",
        realtimeCookieSameSite: "Laz",
        serverCookieEnabled: false,
        enableUrlParameterCaching: false,
        urlParameterCachingOverrides: ["urlParam1", "urlParam2"],
        requestGeolocation: false,
        geolocationCookieDuration: 5,
        context: "home-page",
        smartAssetDecisions: [{PublishID: "e5fab7d8-e744-4ff6-82ed-735afd58543d", ElementID: "someDivName"}],
        enableCrossDomainTracking: false,
        trackingDomains: [],
        realtimeListParameters: ["param1", "param2"],
        visitorProfileMergeMode: 1,
        realtimeContextSearchMode: 0,
        enableDoNotTrack: false,
        isPreview: false
    }, function() {
        // do something here
    });

## Setting RedPoint Web Client Default Initialization Options

Default web client initialization options can be set by defining a globally scoped variable of type RpiWebClientConfig named rpiWebClientDefaults. When RpiWebClient encounters this variable during initialization, its defined properties will be used as the default options in rpiWebClient.init(). Any options passed in to rpiWebClient.init() will override the default properties.

The rpiWebClient.config.js file allows developers to set the default properties of rpiWebClientDefaults. When using rpiWebClient.config.js, it should be included before rpiWebClient-6.4.js on the page.

NOTE: the definitions for the various properties that can be set in rpiWebClientDefaults are found at RpiWebClientConfig

### Example

    var rpiWebClientDefaults = {
        debug: true,
        clientId: "11111111-1111-1111-1111-111111111111",
        serverUrl: "rpirealtime.example.net",
        enableClickTracking: false,
        enablePageVisitTracking: false,
        visitorCookieDuration: 365,
        realtimeCookieDomain: ".example.net",
        realtimeCookieSameSite: "Laz",
        serverCookieEnabled: false,
        enableUrlParameterCaching: false,
        urlParameterCachingOverrides: ["urlParam1", "urlParam2"],
        requestGeolocation: false,
        geolocationCookieDuration: 5,
        context: "home-page",
        smartAssetDecisions: [{PublishID: "e5fab7d8-e744-4ff6-82ed-735afd58543d", ElementID: "someDivName"}],
        enableCrossDomainTracking: false,
        trackingDomains: [],
        realtimeListParameters: ["param1", "param2"],
        visitorProfileMergeMode: 1,
        realtimeContextSearchMode: 0,
        enableDoNotTrack: false,
        isPreview: false
    };

When using rpiWebClientDefaults to set the web client default parameters, the web client can be initialized without specifying the opts parameter.

### Example

    rpiWebClient.init();

## Rendering Decisions

The web client provides options for rendering RPI Realtime Smart Assets (Rule Smart Assets, Goal Smart Assets and Advanced Smart Assets) during and after initialization. Decisions can be rendered during initialization using the contexts and/or smartAssetDecisions properties of RpiWebClientConfig.

The contexts property can be used to specify one or more published context decisions to render when the web client is initialized. The web client uses the ContextTag property of the decision result to determine the DOM element to replace with the decision content. By default, RpiWebClient will replace the contents of the DOM element with either the rg-content-slot or id attribute set to the same value as the ContextTag defined in the decision result.

The smartAssetDecisions can be used to specify one or more SmartAssetDecision objects for rendering decisions by their RPI publish id. The web client uses the ElementID property of the SmartAssetDecision object to determine the DOM element if to replace with the decision content.

### Example

    rpiWebClient.init({
        contexts: ["home-page"],
        smartAssetDecisions: [{ PublishID: 'e5fab7d8-e744-4ff6-82ed-735afd58543d', ElementID: 'promo-tile' }]
    });

The web client provides three methods for rendering decisions post-initialization.

- renderContextDecision - renders a published context decision. The web client uses the ContextTag property of the decision result to determine the DOM element id to replace with the decision content.
- renderContextDecisions - renders one or more published context decisions. The web client uses the ContextTag property of each decision result to determine the DOM element id to replace with the decision content.
- renderSmartAssetDecisions - renders one or more Smart Asset decisions by their RPI publish ids and/or context. The web client uses the ElementID property of each SmartAssetDecision object to determine the DOM element if to replace with the decision content.

When rendering decisions post-initialization, the render methods should be called in the callback to rpiWebClient.init() to ensure that that visitor Id is properly set, prior to requesting a decision.

### Example

        rpiWebClient.init( { contexts: ["browser"] }, function() {
            // do something here

            rpiWebClient.renderSmartAssetDecisions([{PublishID: "39b56ca5-e142-4d49-b14d-ed68cb5860de", ElementID: "test1"}]);
        });

## Passing Realtime Parameters to the Visitor Cache

Realtime parameters can be pushed to the RPI Realtime visitor cache using the rpiWebClient.pushRealtimeParameter() method. The rpiWebClient.pushRealtimeParameter() method queues Realtime parameters until they are flushed or submitted to the RPI Realtime visitor cache. Realtime parameters queued prior to calling rpiWebClient.init() will be submitted to the visitor cache upon initialization.

### Example

    rpiWebClient.pushRealtimeParameter("userId", "987654321");
    rpiWebClient.init( { contexts: ["home-page"] });

Realtime Parameters queued after initialization need to be explicitly flushed using rpiWebClient.flushRealtimeParameters().

### Example

    rpiWebClient.init( { contexts: ["home-page"] }, function() {
        var params = getSomeRealtimeParameters();

        for(var i = 0; i < params.length; i++) {
            rpiWebClient.pushRealtimeParameter(params[i].name, params[i].value);
        }

        rpiWebClient.flushRealtimeParameters(function() {
            // do something with updated visitor
        });
    });

## RPI Realtime Web Events

The web client will send a PageVisit event to RPI Realtime Web Events upon initialization on a web page. The PageVisit event will log the URL and referrer for the page visit. If the page visit originated from an outbound message originating from an RPI channel configured with a Web Events Adapter, the PageVisit event will also log the contact and channel execution ids associated with the message.

Link click tracking can also be enabled by setting the enableClickTracking properties of RpiWebClientConfig to true. When enabled the web client will send a PageLinkClick event to RPI Realtime Web Events whenever a link is clicked on a web page. The PageLinkClick event will log the URL of the link clicked.

Custom web events can also be pushed to RPI Realtime Web Events by calling rpiWebClient.pushWebEvent(). The pushWebEvent method accepts the following parameters:

- state- The name of the event.
- stateValue- The value to assign to the event (e.g. order total)
- extraParam- The additional details to assign to the event (e.g.link click url)
- contentID- The content ID to register the metric for (Goal Drive Assets only)
- metadata- Array of ApiEventMetadata to assign to the event

This method will queue web events until the RPI Realtime visitor id is set. Once a visitor id is set, the queue will flush and subsequent calls to rpiWebClient.pushWebEvent() will be submitted immediately to RPI Realtime Web Events.

### Example

    rpiWebClient.pushWebEvent("conversion", "199.99", null, null, [{Name: "orderNumber", Value: "W09367321"}, {Name: "promoCode", Value: "FALL20"}]);

## Tracking Link Clicks on Decision Result Content

The web client provides attribution functionality on links clicked from the result of an RPI Realtime decision. The RpiDecisionResult object returned when retrieving a decision includes a ResultID property which should be thought of as a unique impression id for an RPI Realtime decision. The ResultID property is set to a data attribute named resultId on all HTML anchor tags during decision content rendering.

When RPI Web Event click tracking is enabled, clicks on links containing the resultId data attribute will have the ResultID value appended to the metadata on the PageLinkClick event.

## RedPoint Web Client Events

The web client raises a number of window events that can be listened for in JavaScript. The web client will return an object relevant to the event type raised in the detail property of the JavaScript event. The web client raises the following events:

- rpiWebClientLoad - raised upon completion of the execution of the RpiWebClient constructor. Returns an instance of RpiWebClient in event.details.
- rpiWebClientPreInit - raised upon setting configuration options for RpiWebClient, prior to initialization. Returns an instance of RpiWebClient in event.details.
- rpiWebClientInitVisitor - raised upon initialization of the RpiWebClient visitor object. Returns an instance of RpiWebClient in event.details.
- rpiWebClientLensActivate - raised upon completion of Realtime Lens activation. Returns an instance of RpiWebClient in event.details.
- rpiWebClientInit - raised upon completion of the execution of the RpiWebClient init() method. Returns an instance of RpiWebClient in event.details.
- rpiWebClientContextDecisionRender - raised upon rendering of all the decision results returned for a context decision. Returns an array of ApiDecisionResult in event.details.
- rpiWebClientSmartAssetDecisionRender - raised upon rendering of the decision result returned for a smart asset request. Returns an ApiDecisionResult in event.details.

-rpiWebClientLookupRequestRender - raised upon completion of the lookup of personalization attributes for decision results published using the "web publish site" option. Returns an array of ApiValueLookupResult in event.details.

- rpiWebClientVisitorSet - raised upon the initial assignment of the RpiWebClient visitor property. Returns a Visitor in event.details.
- rpiWebClientVisitorChange - raised upon the reassignment of the RpiWebClient visitor property. Returns a Visitor in event.details.
- rpiDecisionResultLinkClick - raised upon a link click from a decision result. Returns the ResultID of the rendered decision.
- rpiDecisionResultLoad - raised upon completion of the loading of returned decision results into the data layer. Returns an array of ApiDecisionResult in event.details.
- rpiDecisionTagLoad - raised upon completion of the loading of returned Tag Smart Asset results into the data layer. Returns an array of ApiDecisionResult in event.details.
- rpiDecisionRecommendationLoad - raised upon completion of the loading of returned Product Recommendation Smart Asset results into the data layer. Returns an array of ApiDecisionResult in event.details.

### Example

    window.addEventListener("rpiWebClientContextDecisionRender", function(event) {
        console.log("EVENT: caught rpiWebClientContextDecisionRender..." + JSON.stringify(event.detail));
    });

## Logging

The web client can be configured to enable logging by setting the debug option on RpiWebClientConfig to true. The default logger will write information--including visitor details, service requests and responses--to the browser console.

## Extensibility

Using the JavaScript tight augmentation pattern, the web client can be extended by writing standalone plugins that override the default properties of RpiWebClient. Tight augmentation implies a set loading order to safely override the properties of RpiWebClient. Any plugin JavaScript files will need to be included after rpiWebClient-6.4.js on the page.

In this example we will override RpiWebClient.log--a private method used to log information to the browser console when the RpiWebClientConfig.debug property is set true. The method will be overridden to log debug information to Loggly as well as the browser console.

This example assumes that the Loggly tracking JavaScript has been loaded appropriately on the web page. The example code below should reside in an external JavaScript file and included after rpiWebClient-6.4.js on the page.

### Example

    RpiWebClient.prototype.defaultLogger = RpiWebClient.prototype.log;

    RpiWebClient.prototype.log = function(message, logLevel) {
        // write log message to Loggly
        _LTracker.push('Hello World');

        // execute the default log method
        this.defaultLogger(message, logLevel);
    }

# Browser Compatibility

RpiWebClient was transpiled from Typescript with a target of ECMAScript 6 (ES6).

## RPIWebClient Supported Browsers

Although the RpiWebClient may be compatible with older web browsers, support will only be implied for the web browsers listed below.

Browser | Version | Release Date
--- | --- | ---
Chrome | 51 | May 2016
Firefox | 54 | Jun 2017
Edge | 14 | Aug 2016
Safari | 10 | Sep 2016
Opera | 38 | Jun 2016

Source: W3Schools

# results matching ""

# No results matching ""