Zephr User Guide

Example Script

4 views 0

If you are using the Zephr CDN and have script injection activated, a script is injected to the browser when the page loads.

If you are hosting your own script, the script must be similar to the following example where <database_name>, <write_only_key>, and <audience_token> represent the information entered during the configuration of the Treasure Data extension:

<script type="text/javascript">
     !function(t,e){if(void 0===e[t]){e[t]=function(){e[t].clients.push(this),this._init=[Array.prototype.slice.call(arguments)]},e[t].clients=[];for(var r=["addRecord","blockEvents","fetchServerCookie","fetchGlobalID","fetchUserSegments","resetUUID","ready","setSignedMode","setAnonymousMode","set","trackEvent","trackPageview","trackClicks","unblockEvents"],s=0;s<r.length;s++){var c=r[s];e[t].prototype[c]=function(t){return function(){return this["_"+t]=this["_"+t]||[],this["_"+t].push(Array.prototype.slice.call(arguments)),this}}(c)}var n=document.createElement("script");n.type="text/javascript",n.async=!0,n.src=("https:"===document.location.protocol?"https:":"http:")+"//cdn.treasuredata.com/sdk/3.0/td.min.js";var o=document.getElementsByTagName("script")[0];o.parentNode.insertBefore(n,o)}}("Treasure",this);

     const treasureObject = new Treasure({
       database: "${databaseName}",
       writeKey: "${writeOnlyKey}",
     });

     const makeXMLHttpRequest = (method, url, done, values) => {
       var xhr = new XMLHttpRequest();
       xhr.open(method, url);
       if (method === "POST") {
         xhr.setRequestHeader("Content-type", "application/json");
         xhr.setRequestHeader("Accept", "application/json");
       }
       if (done) {
         xhr.onload = function () {
           done(xhr.status, xhr.response);
         };
         xhr.onerror = function () {
           done(xhr.status, null);
         };
       }
       if (values) {
         xhr.send(JSON.stringify(values));
       } else {
         xhr.send();
       }
     };

     const errorCallback = function (error) {
       console.log(error);
     };

     const callUserProfileEndpoint = function (values) {
       makeXMLHttpRequest(
         "POST",
         "/plugins/public/treasure-data-cdp/user-profile",
         function (status, res) {
           if (+status === 200) {
             console.log("Successfully stored data");
           } else {
             console.log("Unsuccessfully stored data");
           }
         },
         values
       );
     };

     const getCookies = (cname) => {
       const name = cname + "=";
       const cDecoded = decodeURIComponent(document.cookie);
       const cArr = cDecoded.split("; ");
       let key;
       cArr.forEach((val) => {
         if (val.indexOf(name) === 0) key = val.substring(name.length);
       });

       return key;
     };

     const getKeys = (getCookiesFn, callback) => {
       const tdCookie = getCookiesFn("_td");
       const jwtCookie = getCookiesFn("blaize_jwt");
       let emailAddress;

       if (jwtCookie) {
         makeXMLHttpRequest(
           "GET",
           "/blaize/account",
           function (status, res) {
             if (+status === 200) {
               let responseToObj = JSON.parse(res);
               emailAddress = responseToObj["identifiers"]["email_address"] || "";
             }
           },
           null
         );
       }

       callback({
         audienceToken: ${JSON.stringify(audienceToken)},
         keys: {
           emailaddress: emailAddress || "",
           td_client_id: tdCookie || "",
         },
       });
     };

     getKeys(getCookies, (tokensAndKeys) =>
       treasureObject.fetchUserSegments(tokensAndKeys, callUserProfileEndpoint, errorCallback)
     );
   </script>