'use strict' // Global variables // Set the name of the hidden property and the change event for visibility let webchattonic = null let postInit = null let hidden, visibilityChange if (typeof document.hidden !== 'undefined') { // Opera 12.10 and Firefox 18 and later support hidden = 'hidden' visibilityChange = 'visibilitychange' } else if (typeof document.msHidden !== 'undefined') { hidden = 'msHidden' visibilityChange = 'msvisibilitychange' } else if (typeof document.webkitHidden !== 'undefined') { hidden = 'webkitHidden' visibilityChange = 'webkitvisibilitychange' } // Functions const messageEventListener = function(e) { if (webchattonic) { const data = e.data if (data.action === 'sendnotification' && !webchattonic.fcmEnabled) { webchattonic.emitBadge() webchattonic.count++ if (!webchattonic.open) { const newTitle = '(' + webchattonic.count + ') ' + webchattonic.originalTitle document.title = newTitle if (Push) { const onGranted = () => { Push.create(data.title, data.config) } const onDenied = () => { console.log('Notificacion denegada') } if (Push.Permission.has()) { Push.create(data.title, data.config) } else { Push.Permission.request(onGranted, onDenied) } } } } if (data.action === 'sendonfocus') { document.title = webchattonic.originalTitle webchattonic.count = 0 webchattonic.cleanBadge() } if (data.action === 'close') { webchattonic.closeContainer() } if (data.action === 'maximize') { if (webchattonic.maximized) { webchattonic.maximized = false webchattonic.openContainer() } else { webchattonic.maximized = true webchattonic.openContainer(true) } } if (data.action === 'record') { if (data.method === 'start') { webchattonic.startRecording() } else if (data.method === 'stop') { webchattonic.stopRecording() } } if (data.action === 'login' && webchattonic.fcmEnabled) { webchattonic.sendChannelData(webchattonic.firebaseToken) } } } const visibilityChangeEventListener = function() { if (webchattonic) { if (document[hidden]) { webchattonic.focused = false } else { webchattonic.focused = true if (webchattonic.open) { document.title = webchattonic.originalTitle webchattonic.count = 0 webchattonic.cleanBadge() } } } } const readyStateChangeEventListener = function(event) { // // When HTML/DOM elements are ready: // if (event && event.target && event.target.readyState === 'interactive') { // does same as: ..addEventListener("DOMContentLoaded".. // } // When window loaded ( external resources are loaded too- `css`,`src`, etc...) if (event && event.target && event.target.readyState === 'complete' && !webchattonic) { webchattonic = new WebChatTonic() webchattonic.init() } } const readyStateChangeEventListenerDelayed = function(event) { if (2000) { setTimeout(function() { readyStateChangeEventListener(event) }, 2000) } else { readyStateChangeEventListener(event) } } // Classes class WebChatTonic { constructor() { const self = this self.e = window.document self.src = 'https://web.eu.chat-tonic.com/' + 'roche' + '/' + '9b8006aceec9834e0d820c99e490bf5821f1f0014e1a992c62858a29f43da1d8' + '?landing=false&dryRun=false' self.notifications = 0 self.open = false self.count = 0 self.originalTitle = document.title self.container = { object: null, x: null, y: null, prevX: null, prevY: null } self.iframeLoaded = false self.toggleContainer = self.toggleContainer.bind(self) self.cleanMessage = self.cleanMessage.bind(self) self.openContainer = self.openContainer.bind(self) self.closeContainer = self.closeContainer.bind(self) self.updateContext = self.updateContext.bind(self) self.resetConversation = self.resetConversation.bind(self) self.updateMetadata = self.updateMetadata.bind(self) self.verifyContext = self.verifyContext.bind(self) self.sendRecording = self.sendRecording.bind(self) self.getUserMedia = self.getUserMedia.bind(self) self.installFirebase = self.installFirebase.bind(self) self.initializeFirebaseApp = self.initializeFirebaseApp.bind(self) self.initializeFirebaseMessaging = self.initializeFirebaseMessaging.bind(self) self.drag = self.drag.bind(self) self.move = self.move.bind(self) self.drop = self.drop.bind(self) self.landing = 'false' === 'true' self.maximized = false self.stream = null self.record = null self.chunks = [] self.firebaseToken = null self.fcmEnabled = 'false' === 'true' self.focused = true self.textEnabled = 'undefined' !== 'undefined' && 'undefined'.length } init() { const self = this const launcher = self.e.createElement('div') launcher.id = 'web-chattonic-launcher' launcher.style.backgroundColor = '#1F8CEB' if (self.textEnabled) { launcher.style.borderRadius = `${(parseInt('16') + parseInt('13'))}px` const textIcon = self.e.createElement('div') textIcon.id = 'web-chattonic-text-launcher' textIcon.textContent = 'undefined' textIcon.style.textAlign = 'center' textIcon.style.fontSize = `${parseInt('13')}px` textIcon.style.padding = `${parseInt('16')}px ${parseInt('16')}px` textIcon.style.userSelect = 'none' textIcon.style.color = '#FFFFFF' textIcon.style.fontWeight = '600' textIcon.style.fontFamily = 'sans-serif' launcher.appendChild(textIcon) } else { launcher.style.backgroundImage = 'url(' + 'https://s3.eu-central-1.amazonaws.com/web.eu.chat-tonic.com/uploads/roche/app/appData.launcher.image/1NKULRRJ.thumb.png' + ')' launcher.style.width = `${parseInt('60')}px` launcher.style.height = `${parseInt('60')}px` launcher.style.backgroundSize = `${parseInt('60' - 20)}px` launcher.style.borderRadius = '100%' } launcher.addEventListener('click', self.toggleContainer, false) if ('false' === 'true') { launcher.style.backgroundColor = 'transparent' launcher.style.boxShadow = 'none' } const html = self.e.getElementsByTagName('html')[0] html.appendChild(launcher) const badge = self.e.createElement('div') badge.id = 'web-chattonic-badge' badge.style.display = 'none' launcher.appendChild(badge) const message = self.e.createElement('div') message.id = 'web-chattonic-message' message.style.opacity = '0' message.style.visibility = 'hidden' message.style.padding = '0px' message.style.paddingRight = '0px' message.style.backgroundColor = '#1F8CEB' message.style.color = '#FFFFFF' message.style.right = `${parseInt('60' - 15)}px` html.appendChild(message) const container = self.e.createElement('div') container.style.opacity = 0 container.style.visibility = 'hidden' container.id = 'web-chattonic-container' self.e.body.appendChild(container) if (!self.landing) { const dragger = self.e.createElement('div') dragger.style.height = '75' + 'px' dragger.style.width = '235px' dragger.style.position = 'fixed' dragger.id = 'web-chattonic-dragger' self.e.getElementById('web-chattonic-container').appendChild(dragger) dragger.onmousedown = self.drag document.onmousemove = self.move document.onmouseup = self.drop } const iframe = self.e.createElement('iframe') iframe.id = 'web-chattonic-frame' iframe.src = self.src self.e.getElementById('web-chattonic-container').appendChild(iframe) iframe.onload = async () => { try { self.iframeLoaded = true if (postInit && typeof postInit === 'function') { postInit() } if (self.fcmEnabled) { self.installFirebase() } else if (Push && Push.Permission && Push.Permission.has && !Push.Permission.has()) { await Push.Permission.request() } } catch (e) { } } const link = self.e.createElement('link') link.rel = 'stylesheet' link.href = 'https://web.eu.chat-tonic.com/static/webchattonic.css' self.e.head.appendChild(link) window.addEventListener('focus', function(event) { if (self.open) { self.verifyContext() } }, false) const script = document.createElement('script') script.src = 'https://cdnjs.cloudflare.com/ajax/libs/push.js/1.0.5/push.min.js' document.getElementsByTagName('body')[0].appendChild(script) if (self.landing) { self.openContainer(true) } } installFirebase() { const self = this const firebaseAppScript = document.createElement('script') firebaseAppScript.src = 'https://www.gstatic.com/firebasejs/5.9.0/firebase-app.js' firebaseAppScript.onload = self.initializeFirebaseApp document.head.appendChild(firebaseAppScript) } initializeFirebaseApp() { const self = this self.firebase = firebase.initializeApp({ apiKey: 'FCM_APIKEY', authDomain: 'FCM_AUTHhttps://web.eu.chat-tonic.com/', databaseURL: 'FCM_DATABASEURL', projectId: 'FCM_PROJECTID', storageBucket: 'FCM_STORAGEBUCKET', messagingSenderId: 'FCM_MESSAGINGSENDERID' }, 'webchattonic-firebase') const firebaseMessagingScript = document.createElement('script') firebaseMessagingScript.src = 'https://www.gstatic.com/firebasejs/5.9.0/firebase-messaging.js' firebaseMessagingScript.onload = self.initializeFirebaseMessaging document.head.appendChild(firebaseMessagingScript) } initializeFirebaseMessaging() { const self = this self.messaging = self.firebase.messaging() self.messaging.usePublicVapidKey('FCM_PUBLICKEY') self.messaging.requestPermission().then(function() { self.messaging.getToken().then(function(currentToken) { if (currentToken) { self.sendChannelData(currentToken) } }) self.messaging.onTokenRefresh(function() { self.messaging.getToken().then(function(currentToken) { if (currentToken) { self.sendChannelData(currentToken) } }) }) }).catch(function() { // console.log('Unable to get permission to notify.', err) return Promise.resolve() }) } async getUserMedia() { const self = this try { const stream = await navigator.mediaDevices.getUserMedia({ audio: true }) const record = new MediaRecorder(stream) record.ondataavailable = e => { self.chunks.push(e.data) if (self.record.state === 'inactive') { self.sendRecording() } } stream.stop = function() { this.getAudioTracks().forEach(function(track) { track.stop() }) } self.stream = stream self.record = record } catch (e) { console.error('navigator.getUserMedia error:', e) } } toggleContainer() { const self = this const container = self.e.getElementById('web-chattonic-container') const opacity = container.style.opacity if (opacity === '0') { self.openContainer() } else { self.closeContainer() } } openContainer(isLanding) { const self = this self.open = true const container = self.e.getElementById('web-chattonic-container') self.cleanBadge() self.cleanMessage() self.count = 0 document.title = webchattonic && webchattonic.originalTitle container.style.opacity = 1 container.style.visibility = 'visible' const launcher = self.e.getElementById('web-chattonic-launcher') launcher.style.backgroundColor = '#1F8CEB' const body = self.e.getElementsByTagName('body')[0] body.classList.add('overflow-hidden') if (isLanding) { self.container = { object: null, x: null, y: null, prevX: null, prevY: null } container.style.left = self.container.x container.style.top = self.container.y launcher.classList.add('landing') container.classList.add('landing-open') } else { launcher.classList.add('launcher-close') container.classList.add('open') launcher.classList.remove('landing') container.classList.remove('landing-open') } self.verifyContext() } closeContainer() { const self = this if (!self.landing) { self.open = false const container = self.e.getElementById('web-chattonic-container') container.style.opacity = 0 container.style.visibility = 'hidden' self.container = { object: null, x: null, y: null, prevX: null, prevY: null } container.style.left = self.container.x container.style.top = self.container.y self.maximized = false const body = self.e.getElementsByTagName('body')[0] body.classList.remove('overflow-hidden') container.classList.remove('open') container.classList.remove('landing-open') const launcher = self.e.getElementById('web-chattonic-launcher') launcher.style.backgroundColor = '#1F8CEB' if ('false' === 'true') { launcher.style.backgroundColor = 'transparent' launcher.style.boxShadow = 'none' } launcher.classList.remove('landing') launcher.classList.remove('launcher-close') } } emitBadge() { const self = this const container = self.e.getElementById('web-chattonic-container') const opacity = container.style.opacity if (opacity === '0') { const badge = self.e.getElementById('web-chattonic-badge') if (this.notifications === 0) { badge.style.display = 'flex' if (self.textEnabled) { badge.style.position = 'absolute' badge.style.top = '0px' } } this.notifications++ badge.textContent = this.notifications } } emitSound(sounds) { const self = this const container = self.e.getElementById('web-chattonic-container') const opacity = container.style.opacity if (opacity === '0') { const html5Audiotypes = { 'mp3': 'audio/mpeg', 'mp4': 'audio/mp4', 'ogg': 'audio/ogg', 'wav': 'audio/wav' } const html5audio = self.e.createElement('audio') if (html5audio.canPlayType) { if (Array.isArray(sounds)) { sounds.forEach(function(sound) { const sourceel = self.e.createElement('source') sourceel.setAttribute('src', sound) if (sound.match(/.mp3$/i)) { sourceel.setAttribute('type', html5Audiotypes['mp3']) html5audio.appendChild(sourceel) } else if (sound.match(/.mp4$/i)) { sourceel.setAttribute('type', html5Audiotypes['mp4']) html5audio.appendChild(sourceel) } else if (sound.match(/.ogg$/i)) { sourceel.setAttribute('type', html5Audiotypes['ogg']) html5audio.appendChild(sourceel) } else if (sound.match(/.wav$/i)) { sourceel.setAttribute('type', html5Audiotypes['wav']) html5audio.appendChild(sourceel) } }) } html5audio.load() html5audio.pause() html5audio.currentTime = 0 const playPromise = html5audio.play() if (playPromise !== null) { playPromise.catch(() => {}) } } } } emitMessage(text) { const self = this const container = self.e.getElementById('web-chattonic-container') const opacity = container.style.opacity if (opacity === '0') { const message = self.e.getElementById('web-chattonic-message') if (self.textEnabled) { const textElement = self.e.getElementById('web-chattonic-text-launcher') message.style.right = `${(textElement.offsetWidth - 15)}px` } message.style.opacity = '1' message.style.visibility = 'visible' message.style.padding = '10px' message.style.paddingRight = '50px' message.textContent = text } } cleanBadge() { const self = this const badge = self.e.getElementById('web-chattonic-badge') badge.style.display = 'none' this.notifications = 0 badge.textContent = this.notifications } cleanMessage() { const self = this const message = self.e.getElementById('web-chattonic-message') message.style.opacity = '0' message.style.visibility = 'hidden' message.style.padding = '0px' message.style.paddingRight = '0px' message.textContent = '' } addNotification(config) { const self = this if (config) { if (config.count) { self.emitBadge() } if (config.sound) { if (Array.isArray(config.sound)) { self.emitSound(config.sound) } else { self.emitSound(['https://web.eu.chat-tonic.com/static/pop.mp3']) } } if (config.message) { if (typeof config.message === 'string') { self.emitMessage(config.message) } else { self.emitMessage('En que te puedo ayudar?') } clearTimeout(self.cleanMessageAt) if (config.cleanIn && typeof config.cleanIn === 'number') { self.cleanMessageAt = setTimeout(self.cleanMessage, config.cleanIn) } } if (config.container) { if (config.container === 'open') { self.openContainer() } else if (config.container === 'close') { self.closeContainer() } else if (config.container === 'landing') { self.openContainer(true) } else { self.toggleContainer() } } if (config.messageAsUser && typeof config.messageAsUser === 'string') { self.sendMessage(config.messageAsUser) } } } sendMessage(text) { const self = this if (self.iframeLoaded) { const webchatWindow = self.e.getElementById('web-chattonic-frame').contentWindow if (webchatWindow) { webchatWindow.postMessage({ action: 'sendmessage', text }, 'https://web.eu.chat-tonic.com') } } } updateContext(context) { const self = this if (self.iframeLoaded) { const webchatWindow = self.e.getElementById('web-chattonic-frame').contentWindow if (webchatWindow) { webchatWindow.postMessage({ action: 'updatecontext', context }, 'https://web.eu.chat-tonic.com') } } } resetConversation() { const self = this if (self.iframeLoaded) { const webchatWindow = self.e.getElementById('web-chattonic-frame').contentWindow if (webchatWindow) { webchatWindow.postMessage({ action: 'resetconversation' }, 'https://web.eu.chat-tonic.com') } } } updateMetadata(metadata) { const self = this if (self.iframeLoaded) { const webchatWindow = self.e.getElementById('web-chattonic-frame').contentWindow if (webchatWindow) { webchatWindow.postMessage({ action: 'updatemetadata', metadata }, 'https://web.eu.chat-tonic.com') } } } verifyContext() { const self = this if (self.iframeLoaded) { const webchatWindow = self.e.getElementById('web-chattonic-frame').contentWindow if (webchatWindow) { webchatWindow.postMessage({ action: 'verifycontext' }, 'https://web.eu.chat-tonic.com') } } } drag() { const self = this const container = self.e.getElementById('web-chattonic-container') if (!self.maximized) { self.container.object = container self.container.prevX = self.container.x - self.container.object.offsetLeft self.container.prevY = self.container.y - self.container.object.offsetTop } } move(e) { const self = this if (!self.maximized) { if (e.pageX) { self.container.x = e.pageX self.container.y = e.pageY } if (self.container.object) { self.container.object.style.left = (self.container.x - self.container.prevX) + 'px' self.container.object.style.top = (self.container.y - self.container.prevY) + 'px' } } } drop() { const self = this if (!self.maximized && self.container.object) { self.container.object = null } } sendChannelData(token) { const self = this self.firebaseToken = token const webchatWindow = self.e.getElementById('web-chattonic-frame').contentWindow if (webchatWindow) { webchatWindow.postMessage({ action: 'sendchanneltoken', fcmToken: token }, 'https://web.eu.chat-tonic.com') return true } return false } async startRecording() { const self = this if (self.iframeLoaded) { const webchatWindow = self.e.getElementById('web-chattonic-frame').contentWindow await self.getUserMedia() if (self.stream && self.record) { self.record.start() webchatWindow.postMessage({ action: 'record', method: 'blocked', blocked: false }, 'https://web.eu.chat-tonic.com') } else { webchatWindow.postMessage({ action: 'record', method: 'blocked', blocked: true }, 'https://web.eu.chat-tonic.com') } } } stopRecording() { const self = this if (self.stream && self.record) { if (self.record.state !== 'inactive') { self.record.stop() } self.stream.stop() self.stream = null } } sendRecording() { const self = this if (self.iframeLoaded) { const webchatWindow = self.e.getElementById('web-chattonic-frame').contentWindow webchatWindow.postMessage({ action: 'record', audio: self.chunks[0] }, 'https://web.eu.chat-tonic.com') self.chunks = [] } } } window.addEventListener('message', messageEventListener) document.addEventListener(visibilityChange, visibilityChangeEventListener, false) document.addEventListener('readystatechange', readyStateChangeEventListenerDelayed) if (document.readyState === 'complete' && !webchattonic) { webchattonic = new WebChatTonic() webchattonic.init() } // Always keep a new line next for custom scripts postInit = function(){setTimeout(function(){webchattonic.addNotification({"sound":[],"_id":"5f0dd5a6f60e7430b182a473","createdAt":"2020-07-14T15:56:22.395Z","message":"Hola, ¿en qué puedo ayudarte?","sendIn":5000,"app":"5ef24377648e58068eaae2a2","updatedAt":"2020-07-14T15:56:22.398Z"})}, 5000);};