summaryrefslogtreecommitdiffstats
path: root/chrome/browser/resources/chromeos/chromevox/common/interframe.js
blob: 8d7b7fc117f55da7bb99c25783118bbdb72e86ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Tools for interframe communication. To use this class, every
 * window that wants to communicate with its child iframes should enumerate
 * them using document.getElementsByTagName('iframe'), create an ID to
 * associate with that iframe, then call cvox.Interframe.sendIdToIFrame
 * on each of them. Then use cvox.Interframe.sendMessageToIFrame to send
 * messages to that iframe and cvox.Interframe.addListener to receive
 * replies. When a reply is received, it will automatically contain the ID of
 * that iframe as a parameter.
 *
 */

goog.provide('cvox.Interframe');

goog.require('cvox.ChromeVoxJSON');
goog.require('cvox.DomUtil');

/**
 * @constructor
 */
cvox.Interframe = function() {
};

/**
 * The prefix of all interframe messages.
 * @type {string}
 * @const
 */
cvox.Interframe.IF_MSG_PREFIX = 'cvox.INTERFRAME:';

/**
 * The message used to set the ID of a child frame so that it can send replies
 * to its parent frame.
 * @type {string}
 * @const
 */
cvox.Interframe.SET_ID = 'cvox.INTERFRAME_SET_ID';

/**
 * The message used by a child frame to acknowledge an id was set (sent to its
 * parent frame.
 * @type {string}
 * @const
 */
cvox.Interframe.ACK_SET_ID = 'cvox.INTERFRAME_ACK_SET_ID';

/**
 * The ID of this window (relative to its parent farme).
 * @type {number|string|undefined}
 */
cvox.Interframe.id;

/**
 * Array of functions that have been registered as listeners to interframe
 * messages send to this window.
 * @type {Array<function(Object)>}
 */
cvox.Interframe.listeners = [];

/**
 * Maps an id to a function which gets called when a frame first sends an ack
 * for a set id msg.
 @dict {!Object<number|string, function()>}
 * @private
 */
cvox.Interframe.idToCallback_ = {};

/**
 * Flag for unit testing. When false, skips over iframe.contentWindow check
 * in sendMessageToIframe. This is needed because in the wild, ChromeVox may
 * not have access to iframe.contentWindow due to the same-origin security
 * policy. There is no reason to set this outside of a test.
 * @type {boolean}
 */
cvox.Interframe.allowAccessToIframeContentWindow = true;

/**
 * Initializes the cvox.Interframe module. (This is called automatically.)
 */
cvox.Interframe.init = function() {
  cvox.Interframe.messageListener = function(event) {
    if (typeof event.data === 'string' &&
        event.data.indexOf(cvox.Interframe.IF_MSG_PREFIX) == 0) {
      var suffix = event.data.substr(cvox.Interframe.IF_MSG_PREFIX.length);
      var message = /** @type {Object} */ (
          cvox.ChromeVoxJSON.parse(suffix));
      if (message['command'] == cvox.Interframe.SET_ID) {
        cvox.Interframe.id = message['id'];
        message['command'] = cvox.Interframe.ACK_SET_ID;
        cvox.Interframe.sendMessageToParentWindow(message);
      } else if (message['command'] == cvox.Interframe.ACK_SET_ID) {
        cvox.Interframe.id = message['id'];
        var callback = cvox.Interframe.idToCallback_[cvox.Interframe.id];
        callback();
      }
      for (var i = 0, listener; listener = cvox.Interframe.listeners[i]; i++) {
        listener(message);
      }
    }
    return false;
  };
  window.addEventListener('message', cvox.Interframe.messageListener, true);
};

/**
 * Unregister the main window event listener. Intended for clean unit testing;
 * normally there's no reason to call this outside of a test.
 */
cvox.Interframe.shutdown = function() {
  window.removeEventListener('message', cvox.Interframe.messageListener, true);
};

/**
 * Register a function to listen to all interframe communication messages.
 * Messages from a child frame will have a parameter 'id' that you assigned
 * when you called cvox.Interframe.sendIdToIFrame.
 * @param {function(Object)} listener The listener function.
 */
cvox.Interframe.addListener = function(listener) {
  cvox.Interframe.listeners.push(listener);
};

/**
 * Send a message to another window.
 * @param {Object} message The message to send.
 * @param {Window} window The window to receive the message.
 */
cvox.Interframe.sendMessageToWindow = function(message, window) {
  var encodedMessage = cvox.Interframe.IF_MSG_PREFIX +
      cvox.ChromeVoxJSON.stringify(message, null, null);
  window.postMessage(encodedMessage, '*');
};

/**
 * Send a message to another iframe.
 * @param {Object} message The message to send. The message must have an 'id'
 *     parameter in order to be sent.
 * @param {HTMLIFrameElement} iframe The iframe to send the message to.
 */
cvox.Interframe.sendMessageToIFrame = function(message, iframe) {
  if (cvox.Interframe.allowAccessToIframeContentWindow &&
      iframe.contentWindow) {
    cvox.Interframe.sendMessageToWindow(message, iframe.contentWindow);
    return;
  }

  // A content script can't access window.parent, but the page can, so
  // inject a tiny bit of javascript into the page.
  var encodedMessage = cvox.Interframe.IF_MSG_PREFIX +
      cvox.ChromeVoxJSON.stringify(message, null, null);
  var script = document.createElement('script');
  script.type = 'text/javascript';

  // TODO: Make this logic more like makeNodeReference_ inside api.js
  // (line 126) so we can use an attribute instead of a classname
  if (iframe.hasAttribute('id') &&
      document.getElementById(iframe.id) == iframe) {
    // Ideally, try to send it based on the iframe's existing id.
    script.innerHTML =
        'document.getElementById(decodeURI(\'' +
        encodeURI(iframe.id) + '\')).contentWindow.postMessage(decodeURI(\'' +
        encodeURI(encodedMessage) + '\'), \'*\');';
  } else {
    // If not, add a style name and send it based on that.
    var styleName = 'cvox_iframe' + message['id'];
    if (iframe.className === '') {
      iframe.className = styleName;
    } else if (iframe.className.indexOf(styleName) == -1) {
      iframe.className += ' ' + styleName;
    }

    script.innerHTML =
        'document.getElementsByClassName(decodeURI(\'' +
        encodeURI(styleName) +
        '\'))[0].contentWindow.postMessage(decodeURI(\'' +
        encodeURI(encodedMessage) + '\'), \'*\');';
  }

  // Remove the script so we don't leave any clutter.
  document.head.appendChild(script);
  window.setTimeout(function() {
    document.head.removeChild(script);
  }, 1000);
};

/**
 * Send a message to the parent window of this window, if any. If the parent
 * assigned this window an ID, sends back the ID in the reply automatically.
 * @param {Object} message The message to send.
 */
cvox.Interframe.sendMessageToParentWindow = function(message) {
  if (!cvox.Interframe.isIframe()) {
    return;
  }

  message['sourceId'] = cvox.Interframe.id;
  if (window.parent) {
    cvox.Interframe.sendMessageToWindow(message, window.parent);
    return;
  }

  // A content script can't access window.parent, but the page can, so
  // use window.location.href to execute a simple line of javascript in
  // the page context.
  var encodedMessage = cvox.Interframe.IF_MSG_PREFIX +
      cvox.ChromeVoxJSON.stringify(message, null, null);
  window.location.href =
      'javascript:window.parent.postMessage(\'' +
      encodeURI(encodedMessage) + '\', \'*\');';
};

/**
 * Send the given ID to a child iframe.
 * @param {number|string} id The ID you want to receive in replies from
 *     this iframe.
 * @param {HTMLIFrameElement} iframe The iframe to assign.
 * @param {function()=} opt_callback Called when a ack msg arrives from the
 *frame.
 */
cvox.Interframe.sendIdToIFrame = function(id, iframe, opt_callback) {
  if (opt_callback) {
    cvox.Interframe.idToCallback_[id] = opt_callback;
  }
  var message = {'command': cvox.Interframe.SET_ID, 'id': id};
  cvox.Interframe.sendMessageToIFrame(message, iframe);
};

/**
 * Returns true if inside iframe
 * @return {boolean} true if inside iframe.
 */
cvox.Interframe.isIframe = function() {
  return (window != window.parent);
};

cvox.Interframe.init();