1 /* Copyright 2015 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.
8 * This class dispatches window messages (those sent using window.postMessage)
9 * from different sources to the registered handlers.
10 * This should be the only 'message' event listener in this app. Anyone who
11 * wants to listen to window messages should register with this class.
16 /** @suppress {duplicate} */
17 var base = base || {};
22 * @implements {base.Disposable}
24 base.WindowMessageDispatcher = function() {
25 /** @private {Object<string, function(Event):void>} */
29 this.eventHook_ = new base.DomEventHook(
30 window, 'message', this.onMessage_.bind(this), false);
33 base.WindowMessageDispatcher.prototype.dispose = function() {
34 this.unregisterAllHandlers();
36 base.dispose(this.eventHook_);
37 this.eventHook_ = null;
41 * @param {string} source Message source to register handler for.
42 * @param {function(Event):void} handler Handler for the messages from |source|.
45 base.WindowMessageDispatcher.prototype.registerMessageHandler =
46 function(source, handler) {
47 console.assert(Boolean(source), 'No source specified.');
48 console.assert(Boolean(handler), 'No handler specified.');
50 if (source in this.handlers_) {
51 console.error('Cannot register more than one handler for source: ', source);
53 this.handlers_[source] = handler;
58 * @param {string} source Message source to unregister handler for.
61 base.WindowMessageDispatcher.prototype.unregisterMessageHandler =
63 console.assert(Boolean(source), 'No source specified.');
65 if (source in this.handlers_) {
66 delete this.handlers_[source];
68 console.error('Message handler doesn\'t exist for source: ', source);
75 base.WindowMessageDispatcher.prototype.unregisterAllHandlers = function() {
80 * Event handler to process window messages.
82 * @param {Event} event
84 base.WindowMessageDispatcher.prototype.onMessage_ = function(event) {
85 var data = event.data;
86 if (typeof data === 'object') {
88 var source = data['source'];
89 if (source === undefined) {
90 console.error('Missing source field in incoming message: ', data);
94 console.log('object message received from: ', source);
95 var handler = this.handlers_[source];
99 console.error('No handler registered for messages from: ', source);
102 console.error('Unknown window message data type: ', data);