UNPKG

@tonicpow/widget

Version:

TonicPow helps manage visitor sessions, loads any TonicPow Widgets, and fires events.

1 lines 20.7 kB
(()=>{"use strict";const t=function(){var t=this;this.isEnvironmentValid=function(e){return t.environments.includes(e)},this.setEnvironment=function(e){e&&t.isEnvironmentValid(e)&&(t.environment=e,e===t.environmentStaging?(t.apiUrl=t.apiUrlStaging,t.eventsUrl=t.eventsUrlStaging,t.hostUrl=t.hostUrlStaging):e===t.environmentLocal?(t.apiUrl=t.apiUrlLocal,t.eventsUrl=t.eventsUrlLocal,t.hostUrl=t.hostUrlLocal):e===t.environmentProduction&&(t.apiUrl=t.apiUrlProduction,t.eventsUrl=t.eventsUrlProduction,t.hostUrl=t.hostUrlProduction))},this.environmentLocal="local",this.environmentStaging="staging",this.environmentProduction="production",this.apiUrl="https://api.tonicpow.com",this.apiUrlLocal="http://localhost:3000",this.apiUrlStaging="https://api.staging.tonicpow.com",this.apiUrlProduction="https://api.tonicpow.com",this.eventsUrl="https://events.tonicpow.com",this.eventsUrlLocal="http://localhost:3002",this.eventsUrlStaging="https://events.staging.tonicpow.com",this.eventsUrlProduction="https://events.tonicpow.com",this.hostUrl="http://tonicpow.com",this.hostUrlLocal="http://localhost",this.hostUrlStaging="https://web.staging.tonicpow.com",this.hostUrlProduction="https://tonicpow.com",this.customEnvironmentAttribute="data-environment",this.environment="",this.environments=[this.environmentLocal,this.environmentStaging,this.environmentProduction],this.maxSessionDays=60,this.sessionParameterName="tncpw_session",this.challengeParameterName="tncpw_challenge",this.version="v0.0.14",this.widgetDivClass="tonicpow-widget",this.widgetIdAttribute="data-widget-id",this.fbAppId="293952358462196"};var e=function(t,e,n,o){return new(n||(n=Promise))((function(i,r){function a(t){try{s(o.next(t))}catch(t){r(t)}}function c(t){try{s(o.throw(t))}catch(t){r(t)}}function s(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,c)}s((o=o.apply(t,e||[])).next())}))},n=function(t,e){var n,o,i,r,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return r={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function c(r){return function(c){return function(r){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,o&&(i=2&r[0]?o.return:r[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,r[1])).done)return i;switch(o=0,i&&(r=[2&r[0],i.value]),r[0]){case 0:case 1:i=r;break;case 4:return a.label++,{value:r[1],done:!1};case 5:a.label++,o=r[1],r=[0];continue;case 7:r=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||6!==r[0]&&2!==r[0])){a=0;continue}if(3===r[0]&&(!i||r[1]>i[0]&&r[1]<i[3])){a.label=r[1];break}if(6===r[0]&&a.label<i[1]){a.label=i[1],i=r;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(r);break}i[2]&&a.ops.pop(),a.trys.pop();continue}r=e.call(t,a)}catch(t){r=[6,t],o=0}finally{n=i=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}([r,c])}}};const o=function(t,o,i){var r=this;void 0===t&&(t=""),void 0===o&&(o=""),this.sendPing=function(){setTimeout((function(){r.sendEvent("ping",((new Date).getTime()-r.start).toString())}),4e3)},this.detectWidgetClick=function(){document.addEventListener("click",(function(t){return e(r,void 0,void 0,(function(){var e,o,i,r,a;return n(this,(function(n){switch(n.label){case 0:if(e=(t||window.event).target,o=null===(r=null==e?void 0:e.parentElement)||void 0===r?void 0:r.parentElement,!(null===(a=null==o?void 0:o.classList)||void 0===a?void 0:a.contains("tonicpow-widget")))return[3,4];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.sendEvent("widget_click",o.getAttribute(this.config.widgetIdAttribute)||"")];case 2:return n.sent(),[3,4];case 3:return i=n.sent(),console.error("failed to report interaction: widget_click",i),[3,4];case 4:return[2]}}))}))}))},this.detectBounce=function(){window.onbeforeunload=function(){r.sendEvent("bounce",((new Date).getTime()-r.start).toString())}},this.sendChallengeResponse=function(){try{r.sendEvent("challenge",r.challengeGuid)}catch(t){console.error("Failed to send challenge response",t)}},this.detectInteraction=function(){document.addEventListener("mousedown",(function(){return e(r,void 0,void 0,(function(){var t;return n(this,(function(e){switch(e.label){case 0:if(this.interactionSent)return[3,4];e.label=1;case 1:return e.trys.push([1,3,,4]),this.interactionSent=!0,[4,this.sendEvent("interaction","mousedown")];case 2:return e.sent(),[3,4];case 3:return t=e.sent(),console.error("failed to report interaction: mousedown",t),[3,4];case 4:return[2]}}))}))})),document.addEventListener("scroll",(function(){return e(r,void 0,void 0,(function(){var t;return n(this,(function(e){switch(e.label){case 0:if(this.interactionSent)return[3,4];e.label=1;case 1:return e.trys.push([1,3,,4]),this.interactionSent=!0,[4,this.sendEvent("interaction","scroll")];case 2:return e.sent(),[3,4];case 3:return t=e.sent(),console.error("failed to report interaction: scroll",t),[3,4];case 4:return[2]}}))}))})),document.addEventListener("keypress",(function(){return e(r,void 0,void 0,(function(){var t;return n(this,(function(e){switch(e.label){case 0:if(this.interactionSent)return[3,4];e.label=1;case 1:return e.trys.push([1,3,,4]),this.interactionSent=!0,[4,this.sendEvent("interaction","keypress")];case 2:return e.sent(),[3,4];case 3:return t=e.sent(),console.error("failed to report interaction: keypress",t),[3,4];case 4:return[2]}}))}))}))},this.sendEvent=function(t,o){return e(r,void 0,void 0,(function(){var e,i;return n(this,(function(n){switch(n.label){case 0:return this.sessionId||this.challengeGuid?(e=window.location.href,i={v:this.config.version,name:t,location:e,data:o},this.sessionId&&(i.tncpw_session=this.sessionId),[4,fetch("".concat(this.config.eventsUrl,"/v1/events?d=").concat(btoa(JSON.stringify(i))),{method:"get"})]):(console.info("you must call init with a session before sending events"),[2]);case 1:return n.sent(),[2]}}))}))},this.sessionId=t,this.config=i,this.challengeGuid=o,this.interactionSent=!1,this.start=(new Date).getTime(),this.challengeGuid&&this.challengeGuid.length>0?this.sendChallengeResponse():(this.detectInteraction(),this.detectBounce(),this.detectWidgetClick(),this.sendPing())},i=function(){var t=this;this.removeStorage=function(t){try{localStorage.removeItem(t),localStorage.removeItem("".concat(t,"_expiresIn"))}catch(e){return console.log("removeStorage: Error removing key [".concat(t,"] from localStorage: ").concat(JSON.stringify(e))),!1}return!0},this.getStorage=function(e){var n,o=Date.now();try{n=localStorage.getItem("".concat(e,"_expires"))}catch(t){return console.log("getItem: error getting localStorage: ".concat(JSON.stringify(t))),null}if(null==n&&(n=0),n<o)return t.removeStorage(e),null;try{return localStorage.getItem(e)}catch(t){return console.log("getStorage: Error reading key [".concat(e,"] from localStorage: ").concat(JSON.stringify(t))),null}},this.setStorage=function(t,e,n){void 0===n&&(n=null),n=n?Math.abs(n):86400;var o=Date.now()+1e3*n;try{localStorage.setItem(t,e),localStorage.setItem("".concat(t,"_expires"),o.toString())}catch(e){return console.log("setStorage: Error setting key [".concat(t,"] in localStorage: ").concat(JSON.stringify(e))),!1}return!0}};var r,a=function(t,e,n,o){return new(n||(n=Promise))((function(i,r){function a(t){try{s(o.next(t))}catch(t){r(t)}}function c(t){try{s(o.throw(t))}catch(t){r(t)}}function s(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,c)}s((o=o.apply(t,e||[])).next())}))},c=function(t,e){var n,o,i,r,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return r={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function c(r){return function(c){return function(r){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,o&&(i=2&r[0]?o.return:r[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,r[1])).done)return i;switch(o=0,i&&(r=[2&r[0],i.value]),r[0]){case 0:case 1:i=r;break;case 4:return a.label++,{value:r[1],done:!1};case 5:a.label++,o=r[1],r=[0];continue;case 7:r=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||6!==r[0]&&2!==r[0])){a=0;continue}if(3===r[0]&&(!i||r[1]>i[0]&&r[1]<i[3])){a.label=r[1];break}if(6===r[0]&&a.label<i[1]){a.label=i[1],i=r;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(r);break}i[2]&&a.ops.pop(),a.trys.pop();continue}r=e.call(t,a)}catch(t){r=[6,t],o=0}finally{n=i=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}([r,c])}}};!function(t){t.LinkedIn="linkedin",t.PowPing="powping",t.Twitter="twitter",t.Twetch="twetch",t.Facebook="facebook"}(r||(r={}));var s=new(function(){function e(e){var n=this;this.setOreo=function(t,e,n){var o=new Date;o.setTime(o.getTime()+864e5*n),document.cookie="".concat(t,"=").concat(e,";path=/;expires=").concat(o.toUTCString())},this.captureVisitorSession=function(t,e){void 0===t&&(t=""),void 0===e&&(e="");var o=t,i=e,r=new URLSearchParams(window.location.search);return t&&t.length||"undefined"==typeof window||(o=r.get(n.config.sessionParameterName)||null),e&&e.length||"undefined"==typeof window||(i=r.get(n.config.challengeParameterName)||null),o&&o.length>0&&(n.setOreo(n.config.sessionParameterName,o,n.config.maxSessionDays),n.storage.setStorage(n.config.sessionParameterName,o,86400*n.config.maxSessionDays)),i&&i.length>0&&n.storage.setStorage(n.config.challengeParameterName,i,60),{sessionId:o,challengeGuid:i}},this.getVisitorSession=function(){return n.storage.getStorage(n.config.sessionParameterName)},this.loadDivs=function(){return a(n,void 0,void 0,(function(){var t,e,n,o;return c(this,(function(i){switch(i.label){case 0:t=document.getElementsByClassName(this.config.widgetDivClass),e=t.length-1,i.label=1;case 1:if(!(e>=0))return[3,6];if(!(n=t[e]))return console.log("exit early - remove this?"),[3,5];switch(o=n.getAttribute(this.config.customEnvironmentAttribute),this.config.setEnvironment(o||"production"),n.getAttribute("data-widget-type")){case"share-button":return[3,2];case"banner":return[3,3]}return[3,3];case 2:return this.initializeButton(n),[3,5];case 3:return[4,this.initializeBanner(n)];case 4:return i.sent(),[3,5];case 5:return e--,[3,1];case 6:return[2]}}))}))},this.getDataAttributes=function(t){var e={};return[].forEach.call(t.attributes,(function(t){if(/^data-/.test(t.name)){var n=t.name.substr(5).replace(/-(.)/g,(function(t,e){return e.toUpperCase()}));e[n]=t.value}})),e},this.shareButton=function(t,e){n.shareButtons.set(t,e)},this.shareOnPlatform=function(t,e){var o="Check this out 😎 ".concat(t.title," - ").concat(t.short_link_url);switch(e){case r.Facebook:window.open("https://www.facebook.com/dialog/share?quote=".concat(t.title,"&hashtag=ad&href=").concat(t.short_link_url,"&display=popup&app_id=").concat(n.config.fbAppId));break;case r.LinkedIn:window.open("https://www.linkedin.com/shareArticle?mini=true&url=".concat(t.short_link_url,"&title=").concat(t.title,"&description=").concat(o));break;case r.PowPing:window.open("https://powping.com/?text=".concat(o),"_blank");break;case r.Twetch:window.open("https://twetch.app/compose?description=".concat(o),"_blank");break;case r.Twitter:window.open("https://twitter.com/intent/tweet?text=".concat(o),"_blank")}},this.copyText=function(t){var e=document.getElementById("tonicpow-widget-popup");if(e){var n=document.createElement("textarea");n.innerHTML=t,e.appendChild(n),n.select();var o=document.execCommand("copy");if(e.removeChild(n),o){var i=document.getElementById("tonicpow__short-link-text");if(i){var r=i.innerHTML;i.innerHTML="Copied!",setTimeout((function(){i.innerHTML=r}),3e3)}}}},this.closePopup=function(){var t=document.getElementById("tonicpow-widget-popup");t&&t.remove()},this.load=function(){return a(n,void 0,void 0,(function(){var t,e,n,i;return c(this,(function(r){switch(r.label){case 0:if("undefined"==typeof window)return console.error("TonicPow embed only works in the browser"),[2];if(!((t=document.getElementsByClassName(this.config.widgetDivClass))&&t.length>0))return[3,4];r.label=1;case 1:return r.trys.push([1,3,,4]),[4,this.loadDivs()];case 2:return r.sent(),console.log("%c TonicPow widget(s) loaded! ","background: #974CD2; color: #fff"),[3,4];case 3:throw r.sent();case 4:return e=this.captureVisitorSession(),n=e.sessionId,i=e.challengeGuid,(n||i)&&(this.events=new o(n||"",i||"",this.config)),[2]}}))}))},this.config=new t,this.storage=new i,this.widgets=new Map,this.options=e,this.buttonViewsInitialized=!1,this.shareButtons=new Map,this.nrOfButtons=0,"complete"===document.readyState||"interactive"===document.readyState?this.load():document.addEventListener("DOMContentLoaded",(function(){n.load()}))}return e.prototype.initializeButton=function(t){var e=this.getDataAttributes(t);e.buttonId||(t.id="tonicpow-button-id-"+this.nrOfButtons++,e.buttonId=t.id);var n=this.shareButtons.get(e.buttonId)||{};for(var o in e)!e.hasOwnProperty(o)||n&&n.hasOwnProperty(o)||(n[o]=e[o]);var i="";for(var o in n)n.hasOwnProperty(o)&&"string"==typeof n[o]&&(i+="&".concat(o,"=").concat(n[o]));n.width||(n.width="150"),n.height||(n.height="50"),n.targetUrl||(n.targetUrl=encodeURIComponent(document.location.href)),this.shareButtons.set(e.buttonId,n),t.innerHTML="\n <iframe\n src='".concat(this.config.hostUrl,"/share_button.html?targetUrl=").concat(n.targetUrl).concat(i,"'\n class='tonicpow-widget-share-button'\n width='").concat(n.width,"'\n height='").concat(n.height,"'\n />"),this.initializeButtonViews()},e.prototype.initializeButtonViews=function(){var t=this;if(!this.buttonViewsInitialized){var n=document.createElement("style");n.appendChild(document.createTextNode("\n * { clear: all }\n .tonicpow-icon { width: 1.5rem; height: 1.5rem; cursor: pointer; margin: auto; }\n .tonicpow-icon > object { pointer-events: none; }\n .tonicpow-widget-share-button { border: none; }\n .tonicpow-widget-share-button > iframe { overflow: hidden; }\n .tonicpow-modal { font-family: Nunito, Arial; display: flex; align-items: center; padding: 0 1em; text-align: center; width: 100%; height: 100%; position: fixed; top: 0; left: 0; }\n .tonicpow-modal__overlay { background: black; bottom: 0; left: 0; position: fixed; right: 0; text-align: center; top: 0; z-index: -800; opacity: 0.5; }\n .tonicpow-modal__box { padding: 25px; position: relative; margin: 1em auto; max-width: 500px; width: 90%; background-color: #fff; border-radius: 12px; }\n .tonicpow-modal__box > h2 { margin-top: 0; text-align: left; }\n .tonicpow-modal__box > h2 > .tonicpow-modal__close { float: right; cursor: pointer; }\n .tonicpow-modal__box > .tonicpow-modal__grid { padding: 2rem; display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); }\n .tonicpow-modal__box > .tonicpow-modal__campaign { position: relative; border: 1px solid #f2f2f2; }\n .tonicpow-modal__box > .tonicpow-modal__campaign > .tonicpow-modal__campaign_title { display: flex; justify-content: center; align-items: center; position: absolute; border-radius: 0 0 .5rem .5rem; background: rgba(0,0,0,.5); left: 0; color: white; bottom: 0; width: 100%; height: 2rem; }\n .tonicpow-modal__box > .tonicpow-modal__campaign > .tonicpow-modal__campaign_ppc { position: absolute; background: rgba(0,200,0,.5); right: .5rem; color: white; top: .5rem; }\n .tonicpow-modal__box > .tonicpow-modal__campaign > img { display: block; border-radius: .5rem; width: 100% }\n ")),document.head.appendChild(n),this.buttonViewsInitialized=!0,window.addEventListener("message",(function(n){if(n.data&&n.data.buttonId&&"tonicpow"===n.data.source){var o=t.shareButtons.get(n.data.buttonId)||{};n.data.error?o.hasOwnProperty("onError")&&"function"==typeof o.onError?o.onError(n.data):e.showPopup({title:"ERROR: "+n.data.error,shortLink:n.data.message}):o.hasOwnProperty("onSuccess")&&"function"==typeof o.onSuccess?o.onSuccess(n.data):e.showPopup({title:"Share & Earn",shortLink:n.data.shortLink})}}))}},e.showPopup=function(t){var e,n,o,i,a,c="".concat(window.TonicPow.config.hostUrl,"/images/icons/copyIcon.svg"),s="".concat(window.TonicPow.config.hostUrl,"/images/icons/facebookIcon.svg"),l="".concat(window.TonicPow.config.hostUrl,"/images/icons/twitterIcon.svg"),d="".concat(window.TonicPow.config.hostUrl,"/images/icons/twetchIcon.svg"),u="".concat(window.TonicPow.config.hostUrl,"/images/icons/closeIcon.svg"),h="".concat(window.TonicPow.config.hostUrl,"/images/image_placeholder_tonicpow.png"),p=document.createElement("div");p.id="tonicpow-widget-popup",p.classList.add("tonicpow-modal");var g=document.createElement("div");g.classList.add("tonicpow-modal__grid");var w=document.createElement("div");w.classList.add("tonicpow-icon"),w.onclick=function(){var e;return window.TonicPow.copyText(null===(e=t.shortLink)||void 0===e?void 0:e.short_link_url)};var m=document.createElement("object");m.setAttribute("data",c),m.setAttribute("width","24"),m.setAttribute("height","24"),w.appendChild(m);var f=document.createElement("div");f.classList.add("tonicpow-icon"),f.onclick=function(){return window.TonicPow.shareOnPlatform(t.shortLink,r.Facebook)};var v=document.createElement("object");v.setAttribute("data",s),v.setAttribute("width","24"),v.setAttribute("height","24"),f.appendChild(v);var b=document.createElement("div");b.classList.add("tonicpow-icon"),b.onclick=function(){return window.TonicPow.shareOnPlatform(t.shortLink,r.Twitter)};var y=document.createElement("object");y.setAttribute("data",l),y.setAttribute("width","24"),y.setAttribute("height","24"),b.appendChild(y);var _=document.createElement("div");_.classList.add("tonicpow-icon"),_.onclick=function(){return window.TonicPow.shareOnPlatform(t.shortLink,r.Twetch)};var k=document.createElement("object");k.setAttribute("data",d),k.setAttribute("width","24"),k.setAttribute("height","24"),_.appendChild(k),g.appendChild(_),g.appendChild(b),g.appendChild(f),g.appendChild(w);var S=document.createElement("div");S.classList.add("tonicpow-modal__box"),S.innerHTML="\n <h2>\n ".concat(t.title,'\n <div class="tonicpow-modal__close tonicpow-icon" onclick="TonicPow.closePopup();">\n <object data="').concat(u,'"></object>\n </div>\n </h2>\n <div class="tonicpow-modal__campaign">\n <img class="tonicpow-modal__campaign_image" src="').concat((null===(n=null===(e=t.shortLink)||void 0===e?void 0:e.image_url)||void 0===n?void 0:n.length)?null===(o=t.shortLink)||void 0===o?void 0:o.image_url:h,'" />\n <div class="tonicpow-modal__campaign_title">').concat((null===(i=t.shortLink)||void 0===i?void 0:i.title.length)?t.shortLink.title:"TonicPow Campaign",'</div>\n </div>\n <p id="tonicpow__short-link-text">').concat(null===(a=t.shortLink)||void 0===a?void 0:a.short_link_url,"</p> \n\n "),S.appendChild(g),p.innerHTML='<div>\n <div class="tonicpow-modal__overlay" onclick="TonicPow.closePopup();"></div>\n </div>\n ',p.appendChild(S),document.body.appendChild(p)},e.prototype.initializeBanner=function(t){return a(this,void 0,void 0,(function(){var e,n,o,i;return c(this,(function(r){switch(r.label){case 0:if(!(e=t.getAttribute(this.config.widgetIdAttribute)))return console.log("".concat(e," not found")),[2];this.widgets.set(e,null),r.label=1;case 1:return r.trys.push([1,6,,7]),[4,fetch("".concat(this.config.apiUrl,"/v1/widgets/display/").concat(e,"?provider=embed-").concat(this.config.version))];case 2:return n=r.sent(),o=void 0,403!==n.status?[3,3]:(console.info("".concat(n.status,": Domain not allowed")),o={link_url:this.config.hostUrl,image_url:"".concat(this.config.hostUrl,"/images/widgetFallback.svg")},[3,5]);case 3:return[4,n.json()];case 4:o=r.sent(),r.label=5;case 5:return i=encodeURIComponent(o.title),t.innerHTML="\n <a href='".concat(o.link_url,"?utm_source=tonicpow-widgets&utm_medium=widget&utm_campaign=").concat(e,"&utm_content=").concat(i,"' \n style='display: inline-block' \n rel='noopener sponsored' \n target='_blank'>\n <img src='").concat(o.image_url,"' \n width='").concat(o.width,"' \n height='").concat(o.height,"' \n alt='").concat(o.title,"'\n loading='lazy' />\n </a>"),t.setAttribute("data-width",o.width),t.setAttribute("data-height",o.height),this.widgets.set(e,o),this.options&&this.options.onWidgetLoaded&&(o.id=e,this.options.onWidgetLoaded(o)),[3,7];case 6:throw r.sent();case 7:return[2]}}))}))},e}());window.TonicPow=s||{}})();