1// Copyright 2014 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5/** 6 * @fileoverview 7 * Class to communicate with the background scripts via chrome runtime 8 * messages to 9 * 1. Forward session state notifications 10 * 2. Closes the window when the session terminates 11 */ 12 13'use strict'; 14 15/** @suppress {duplicate} */ 16var remoting = remoting || {}; 17 18/** 19 * @constructor 20 * @param {string} senderId id of the current tab or window. 21 */ 22remoting.HangoutSession = function(senderId) { 23 /** 24 * @private 25 * @type {chrome.runtime.Port} 26 */ 27 this.port_ = null; 28 29 /** 30 * @private 31 * @type {string} 32 */ 33 this.senderId_ = senderId; 34}; 35 36remoting.HangoutSession.prototype.init = function() { 37 var portName = 'it2me.helper.webapp@' + this.senderId_; 38 this.port_ = chrome.runtime.connect({name: portName}); 39 40 remoting.hangoutSessionEvents.addEventListener( 41 remoting.hangoutSessionEvents.sessionStateChanged, 42 this.onSessionStateChanged_.bind(this)); 43}; 44 45/** 46 * @param {remoting.ClientSession.State} state 47 */ 48remoting.HangoutSession.prototype.onSessionStateChanged_ = function(state) { 49 var State = remoting.ClientSession.State; 50 try { 51 this.port_.postMessage({method: 'sessionStateChanged', state: state}); 52 } catch (e) { 53 // postMessage will throw an exception if the port is disconnected. 54 // We can safely ignore this exception. 55 var error = /** @type {Error} */ e; 56 console.error(error); 57 } finally { 58 if (state === State.FAILED || state === State.CLOSED) { 59 // close the current window 60 if (base.isAppsV2()) { 61 chrome.app.window.current().close(); 62 } else { 63 window.close(); 64 } 65 } 66 } 67}; 68 69 70/** 71 * remoting.clientSession does not exist until the session is connected. 72 * hangoutSessionEvents serves as a global event source to plumb session 73 * state changes until we cleanup clientSession and sessionConnector. 74 * @type {base.EventSource} 75 */ 76remoting.hangoutSessionEvents = new base.EventSource(); 77 78/** @type {string} */ 79remoting.hangoutSessionEvents.sessionStateChanged = "sessionStateChanged"; 80 81remoting.hangoutSessionEvents.defineEvents( 82 [remoting.hangoutSessionEvents.sessionStateChanged]);