UNPKG

cbp-lib

Version:

Libraries for cbp

83 lines (70 loc) 2.63 kB
'use strict' import {Log} from '../_helpers/Log' let _ = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : {}; let $ = _.document export class SessionIFrame { constructor(callback, metadata, interval = 1000*120) { this._callback = callback this._interval = interval this._metadata = metadata this._iframe_origin = metadata.authorization_server this._iframe = $.createElement('iframe') this._iframe.style.visibility = 'hidden' this._iframe.style.display = 'none' this._iframe.style.height = '0' this._iframe.style.width = '0' this._iframe.src = this._metadata.check_session_iframe } load() { return new Promise((resolve) => { this._iframe.onload = () => { resolve() } $.body.appendChild(this._iframe) this._recieveMessage = this._message.bind(this) _.addEventListener("message", this._recieveMessage, false) }) } start(session_state) { if (this._session_state !== session_state) { Log.debug("SessionIFrame.start" ) this.stop() this._session_state = session_state let check = () => { Log.debug("SessionIFrame.check : Checking session state..." ) let text = this._metadata.client_id + " " + this._session_state this._iframe.contentWindow.postMessage(text, this._iframe_origin) } check() // set up timer call this._timer = _.setInterval(check, this._interval) } } _message(e) { Log.debug("SessionIFrame._message: called message function...." ) if (e.origin === this._iframe_origin && e.source === this._iframe.contentWindow) { if (e.data === 'error') { Log.error("SessionIFrame: Error " + e.data) this.stop() } else if(e.data === 'changed') { // call the callback function Log.debug("SessionIFrame : session changed from op..." ) this.stop() this._callback(e.data) } else { Log.debug("SessionIFrame: " + e.data) } } } stop() { this._session_state = null if (this._timer) { Log.debug("SessionIFrame: stopping check state...") _.clearInterval(this._timer) this._timer = null } } }