How to use the JSAPI with Promises

You can download the zip file, which includes the code from this example. Do not forget to change your Server API Key in the snippet.js script: chatexample.zip

The following example uses the latest snippet with Promises. The example works with all browsers, including MS Edge and Internet Explorer.

First, let's see what the new snippet with Promises looks like.

snippet.js:

/* unblu snippet V4.2.20160712 */
unblu = {APIKEY: "MZsy5sFESYqU7MawXZgR_w", SERVER: "http://localhost:8080"};

(function() {
    unblu.c = [];
    unblu.registerApiConsumer = function(callback, errorCallback, apiNames) {
        if (callback instanceof Array) {
            if (window["Promise"]) {
                return new Promise(function(resolve, reject) {
                    unblu.c.push({a: callback, c: resolve, e: reject});
                });
            } else {
                throw new Error("Promise not available");
            }
        }

        unblu.c.push({a: apiNames, c: callback, e: errorCallback});
    }
    unblu.setLocale = function(locale) {
        unblu.l = locale;
    }
    if (!window["x-unblu-tmp-window-name"]) window["x-unblu-tmp-window-name"]=window.name;
    var q = document.getElementsByTagName("script")[0];
    if (q) {
        var g = document.createElement("script");
        g.setAttribute("src", unblu.SERVER + "/unblu/starter.js");
        g.setAttribute("type", "text/javascript");
        g.setAttribute("defer","defer");
        q.parentNode.appendChild(g);
    }
})();

In order for this code snippet to work with MS Edge, Internet Explorer and other browsers, which do not recognize Promises, we will need the following code. This code adds Promises functionality to your browser, if needed.

(function(t){function z(){for(var a=0;a<g.length;a++)g[a][0](g[a][1]);g=[];m=!1}function n(a,b){g.push([a,b]);m||(m=!0,A(z,0))}function B(a,b){function c(a){p(b,a)}function h(a){k(b,a)}try{a(c,h)}catch(d){h(d)}}function u(a){var b=a.owner,c=b.state_,b=b.data_,h=a[c];a=a.then;if("function"===typeof h){c=l;try{b=h(b)}catch(d){k(a,d)}}v(a,b)||(c===l&&p(a,b),c===q&&k(a,b))}function v(a,b){var c;try{if(a===b)throw new TypeError("A promises callback cannot return that same promise.");if(b&&("function"===
typeof b||"object"===typeof b)){var h=b.then;if("function"===typeof h)return h.call(b,function(d){c||(c=!0,b!==d?p(a,d):w(a,d))},function(b){c||(c=!0,k(a,b))}),!0}}catch(d){return c||k(a,d),!0}return!1}function p(a,b){a!==b&&v(a,b)||w(a,b)}function w(a,b){a.state_===r&&(a.state_=x,a.data_=b,n(C,a))}function k(a,b){a.state_===r&&(a.state_=x,a.data_=b,n(D,a))}function y(a){var b=a.then_;a.then_=void 0;for(a=0;a<b.length;a++)u(b[a])}function C(a){a.state_=l;y(a)}function D(a){a.state_=q;y(a)}function e(a){if("function"!==
typeof a)throw new TypeError("Promise constructor takes a function argument");if(!1===this instanceof e)throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");this.then_=[];B(a,this)}var f=t.Promise,s=f&&"resolve"in f&&"reject"in f&&"all"in f&&"race"in f&&function(){var a;new f(function(b){a=b});return"function"===typeof a}();"undefined"!==typeof exports&&exports?(exports.Promise=s?f:e,exports.Polyfill=e):"function"==
typeof define&&define.amd?define(function(){return s?f:e}):s||(t.Promise=e);var r="pending",x="sealed",l="fulfilled",q="rejected",E=function(){},A="undefined"!==typeof setImmediate?setImmediate:setTimeout,g=[],m;e.prototype={constructor:e,state_:r,then_:null,data_:void 0,then:function(a,b){var c={owner:this,then:new this.constructor(E),fulfilled:a,rejected:b};this.state_===l||this.state_===q?n(u,c):this.then_.push(c);return c.then},"catch":function(a){return this.then(null,a)}};e.all=function(a){if("[object Array]"!==
Object.prototype.toString.call(a))throw new TypeError("You must pass an array to Promise.all().");return new this(function(b,c){function h(a){e++;return function(c){d[a]=c;--e||b(d)}}for(var d=[],e=0,f=0,g;f<a.length;f++)(g=a[f])&&"function"===typeof g.then?g.then(h(f),c):d[f]=g;e||b(d)})};e.race=function(a){if("[object Array]"!==Object.prototype.toString.call(a))throw new TypeError("You must pass an array to Promise.race().");return new this(function(b,c){for(var e=0,d;e<a.length;e++)(d=a[e])&&"function"===
typeof d.then?d.then(b,c):b(d)})};e.resolve=function(a){return a&&"object"===typeof a&&a.constructor===this?a:new this(function(b){b(a)})};e.reject=function(a){return new this(function(b,c){c(a)})}})("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this);

The next step is to add the script for starting a chat session. Here is a short function you can add to the startChat.js file.

startChat.js:

startTestChat = function () {
    console.log("test chat session");
    var unbluAPI;
    unblu.registerApiConsumer(["core.visitor"]).then(function(api) {
        unbluAPI = api;
        return unbluAPI.core.visitor.agentinfo.AgentInformation.isAgentPresent();
    }).then(function(agentPresent){
        return unbluAPI.core.visitor.session.Session.startChatSession("Johny");
    }).then(function(sessionInfo){
        console.log("chat session started");
    })["catch"](function(error){
        console.log("error in chat session");
    });
}

The last step is to create an HTML page and insert all of these JavaScripts into it. This example adds a link which calls the startTestChat() function onclick event.

chatExample.html:

<!DOCTYPE html>
<html>
<head>
  <title>JSAPI Chat Example</title>
  <script type="text/javascript" src="snippet.js"></script>
  <script type="text/javascript" src="promise.min.js"></script>
  <script type="text/javascript" src="startChat.js"></script>
</head>
<body>
<h1>Welcome to your Chat Example App</h1>
<p>You can start a chat using the JSAPI by clicking the link below</p>
<a href="#" title="Start Chart" onclick="startTestChat()" itemprop="url">
<span itemprop="name">Start chat</span>
</a>
</body>
</html>
  • deploycloud
  • deployonprem

results matching ""

    No results matching ""