Debian Codegraph @

closure-library/closure/goog/window/window_test.js

raw
1 // Copyright 2009 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 goog.provide('goog.windowTest');
16 goog.setTestOnly('goog.windowTest');
17
18 goog.require('goog.Promise');
19 goog.require('goog.dom');
20 goog.require('goog.dom.TagName');
21 goog.require('goog.events');
22 goog.require('goog.functions');
23 goog.require('goog.html.SafeUrl');
24 goog.require('goog.labs.userAgent.browser');
25 goog.require('goog.labs.userAgent.engine');
26 goog.require('goog.labs.userAgent.platform');
27 goog.require('goog.string');
28 goog.require('goog.testing.PropertyReplacer');
29 goog.require('goog.testing.TestCase');
30 goog.require('goog.testing.jsunit');
31 goog.require('goog.window');
32
33 var newWin;
34 var REDIRECT_URL_PREFIX = 'window_test.html?runTests=';
35 var WIN_LOAD_TRY_TIMEOUT = 100;
36 var MAX_WIN_LOAD_TRIES = 50; // 50x100ms = 5s waiting for window to load.
37
38 var stubs = new goog.testing.PropertyReplacer();
39
40
41 function shouldRunTests() {
42 // MS Edge has a bunch of flaky test failures around window.open.
43 // TODO(joeltine): Remove this when http://b/25455129 is fixed.
44 return !goog.labs.userAgent.browser.isEdge();
45 }
46
47
48 function setUpPage() {
49 var anchors = goog.dom.getElementsByTagNameAndClass(
50 goog.dom.TagName.DIV, 'goog-like-link');
51 for (var i = 0; i < anchors.length; i++) {
52 goog.events.listen(anchors[i], 'click', function(e) {
53 goog.window.open(goog.dom.getTextContent(e.target), {'noreferrer': true});
54 });
55 }
56 goog.testing.TestCase.getActiveTestCase().promiseTimeout = 60000; // 60s
57 }
58
59
60 // To test goog.window.open we open a new window with this file again. Once
61 // the new window parses this file it sets this variable to true, indicating
62 // that the parent test may check window properties like referrer and location.
63 var newWinLoaded = true;
64
65
66 function setUp() {
67 newWin = undefined;
68 }
69
70
71 function tearDown() {
72 if (newWin) {
73 newWin.close();
74 }
75 stubs.reset();
76 }
77
78
79 /**
80 * Uses setTimeout to poll a new window for the "newWinLoaded" variable, which
81 * is set once the JavaScript is evaluated in that window.
82 *
83 * @param {Window} win
84 * @return {!goog.Promise<!Window>} Promise for a window that resolves once the
85 * window has loaded.
86 */
87 function waitForTestWindow(win) {
88 return new goog.Promise(function(resolve, reject) {
89 var checkWindow = function(numTries) {
90 if (!win) {
91 fail('Could not open new window. Check if popup blocker is enabled.');
92 }
93 if (numTries > MAX_WIN_LOAD_TRIES) {
94 fail('Window did not load after maximum number of checks.');
95 }
96
97 if (win.newWinLoaded) {
98 resolve(win);
99 } else {
100 window.setTimeout(checkWindow, WIN_LOAD_TRY_TIMEOUT);
101 }
102 };
103 checkWindow(0);
104 });
105 }
106
107
108 /**
109 * Opens a window and then verifies that the new window has the expected
110 * properties.
111 *
112 * @param {boolean} noreferrer Whether to test the noreferrer option.
113 * @param {string} urlParam Url param to append to the url being opened.
114 * @param {boolean} encodeUrlParam_opt Whether to percent-encode urlParam. This
115 * is needed because IE will not encode it automatically like other browsers
116 * browser and the Closure test server will 400 on certain characters in
117 * the URL (like '<' and '"').
118 * @return {!goog.Promise} Promise that resolves once the test is complete.
119 */
120 function doTestOpenWindow(noreferrer, urlParam, encodeUrlParam_opt) {
121 if (encodeUrlParam_opt) {
122 urlParam = encodeURIComponent(urlParam);
123 }
124 // TODO(mlourenco): target is set because goog.window.open() will currently
125 // allow it to be undefined, which in IE seems to result in the same window
126 // being reused, instead of a new one being created. If goog.window.open()
127 // is fixed to use "_blank" by default then target can be removed here.
128 newWin = goog.window.open(
129 REDIRECT_URL_PREFIX + urlParam,
130 {'noreferrer': noreferrer, 'target': '_blank'});
131
132 return waitForTestWindow(newWin).then(function(win) {
133 verifyWindow(win, noreferrer, urlParam);
134 });
135 }
136
137
138 /**
139 * Asserts that a newly created window has the correct parameters.
140 *
141 * @param {Window} win
142 * @param {boolean} noreferrer Whether the noreferrer option is being tested.
143 * @param {string} urlParam Url param appended to the url being opened.
144 */
145 function verifyWindow(win, noreferrer, urlParam) {
146 if (noreferrer) {
147 assertEquals(
148 'Referrer should have been stripped', '', win.document.referrer);
149 }
150
151 var winUrl = decodeURI(win.location);
152 var expectedUrlSuffix = decodeURI(urlParam);
153 assertTrue(
154 'New window href should have ended with <' + expectedUrlSuffix +
155 '> but was <' + winUrl + '>',
156 goog.string.endsWith(winUrl, expectedUrlSuffix));
157 }
158
159
160 function testOpenNotEncoded() {
161 return doTestOpenWindow(false, 'bogus~');
162 }
163
164
165 function testOpenEncoded() {
166 return doTestOpenWindow(false, 'bogus%7E');
167 }
168
169
170 function testOpenEncodedPercent() {
171 // Intent of url is to pass %7E to the server, so it was encoded to %257E .
172 return doTestOpenWindow(false, 'bogus%257E');
173 }
174
175
176 function testOpenNotEncodedHidingReferrer() {
177 return doTestOpenWindow(true, 'bogus~');
178 }
179
180
181 function testOpenEncodedHidingReferrer() {
182 return doTestOpenWindow(true, 'bogus%7E');
183 }
184
185
186 function testOpenEncodedPercentHidingReferrer() {
187 // Intent of url is to pass %7E to the server, so it was encoded to %257E .
188 return doTestOpenWindow(true, 'bogus%257E');
189 }
190
191
192 function testOpenSemicolon() {
193 return doTestOpenWindow(true, 'beforesemi;aftersemi');
194 }
195
196
197 function testTwoSemicolons() {
198 return doTestOpenWindow(true, 'a;b;c');
199 }
200
201
202 function testOpenAmpersand() {
203 return doTestOpenWindow(true, 'this&that');
204 }
205
206
207 function testOpenSingleQuote() {
208 return doTestOpenWindow(true, "'");
209 }
210
211
212 function testOpenDoubleQuote() {
213 return doTestOpenWindow(true, '"', goog.labs.userAgent.browser.isIE());
214 }
215
216
217 function testOpenTag() {
218 return doTestOpenWindow(true, '<', goog.labs.userAgent.browser.isIE());
219 }
220
221
222 function testOpenWindowSanitization() {
223 var navigatedUrl;
224 var mockWin = {open: function(url) { navigatedUrl = url; }};
225
226 goog.window.open('javascript:evil();', {}, mockWin);
227 assertEquals(goog.html.SafeUrl.INNOCUOUS_STRING, navigatedUrl);
228
229 // Try the other code path
230 goog.window.open({href: 'javascript:evil();'}, {}, mockWin);
231 assertEquals(goog.html.SafeUrl.INNOCUOUS_STRING, navigatedUrl);
232
233 goog.window.open('javascript:\'\'', {}, mockWin);
234 assertEquals(goog.html.SafeUrl.INNOCUOUS_STRING, navigatedUrl);
235
236 goog.window.open('about:blank', {}, mockWin);
237 assertEquals(goog.html.SafeUrl.INNOCUOUS_STRING, navigatedUrl);
238 }
239
240
241 function testOpenWindowNoSanitization() {
242 var navigatedUrl;
243 var mockWin = {open: function(url) { navigatedUrl = url; }};
244
245 goog.window.open('', {}, mockWin);
246 assertEquals('', navigatedUrl);
247
248 goog.window.open(goog.html.SafeUrl.ABOUT_BLANK, {}, mockWin);
249 assertEquals('about:blank', navigatedUrl);
250 }
251
252
253 function testOpenBlank() {
254 newWin = goog.window.openBlank('Loading...');
255 var urlParam = 'bogus~';
256 newWin.location.href = REDIRECT_URL_PREFIX + urlParam;
257 return waitForTestWindow(newWin).then(function() {
258 verifyWindow(newWin, false, urlParam);
259 });
260 }
261
262
263 function testOpenBlankReturnsNullPopupBlocker() {
264 var mockWin = {
265 // emulate popup-blocker by returning a null window on open().
266 open: function() { return null; }
267 };
268 var win = goog.window.openBlank('', {noreferrer: true}, mockWin);
269 assertNull(win);
270 }
271
272
273 function testOpenBlankEscapesSafely() {
274 // Opening a window with javascript: and then reading from its document.body
275 // is problematic because in some browsers the document.body won't have been
276 // updated yet, and in some IE versions the parent window does not have
277 // access to document.body in new blank window.
278 var navigatedUrl;
279 var mockWin = {open: function(url) { navigatedUrl = url; }};
280
281 // Test string determines that all necessary escaping transformations happen,
282 // and that they happen in the right order (HTML->JS->URI).
283 // - " which would be escaped by HTML escaping and JS string escaping. It
284 // should be HTML escaped.
285 // - \ which would be escaped by JS string escaping and percent-encoded
286 // by encodeURI(). It gets JS string escaped first (to two '\') and then
287 // percent-encoded.
288 var win = goog.window.openBlank('"\\', {}, mockWin);
289 assertEquals('javascript:"&quot;%5C%5C"', navigatedUrl);
290 }
291
292
293 function testOpenIosBlank() {
294 if (!goog.labs.userAgent.engine.isWebKit() || !window.navigator) {
295 // Don't even try this on IE8!
296 return;
297 }
298 var attrs = {};
299 var dispatchedEvent = null;
300 var element = {
301 setAttribute: function(name, value) { attrs[name] = value; },
302 dispatchEvent: function(event) { dispatchedEvent = event; }
303 };
304 stubs.replace(window.document, 'createElement', function(name) {
305 if (name == goog.dom.TagName.A) {
306 return element;
307 }
308 return null;
309 });
310 stubs.set(window.navigator, 'standalone', true);
311 stubs.replace(goog.labs.userAgent.platform, 'isIos', goog.functions.TRUE);
312
313 var newWin = goog.window.open('http://google.com', {target: '_blank'});
314
315 // This mode cannot return a new window.
316 assertNotNull(newWin);
317 assertUndefined(newWin.document);
318
319 // Attributes.
320 // element.href is directly set through goog.dom.safe.setAnchorHref, not with
321 // element.setAttribute.
322 assertEquals('http://google.com', element.href);
323 assertEquals('_blank', attrs['target']);
324 assertEquals('', attrs['rel'] || '');
325
326 // Click event.
327 assertNotNull(dispatchedEvent);
328 assertEquals('click', dispatchedEvent.type);
329 }
330
331
332 function testOpenIosBlankNoreferrer() {
333 if (!goog.labs.userAgent.engine.isWebKit() || !window.navigator) {
334 // Don't even try this on IE8!
335 return;
336 }
337 var attrs = {};
338 var dispatchedEvent = null;
339 var element = {
340 setAttribute: function(name, value) { attrs[name] = value; },
341 dispatchEvent: function(event) { dispatchedEvent = event; }
342 };
343 stubs.replace(window.document, 'createElement', function(name) {
344 if (name == goog.dom.TagName.A) {
345 return element;
346 }
347 return null;
348 });
349 stubs.set(window.navigator, 'standalone', true);
350 stubs.replace(goog.labs.userAgent.platform, 'isIos', goog.functions.TRUE);
351
352 var newWin = goog.window.open(
353 'http://google.com', {target: '_blank', noreferrer: true});
354
355 // This mode cannot return a new window.
356 assertNotNull(newWin);
357 assertUndefined(newWin.document);
358
359 // Attributes.
360 // element.href is directly set through goog.dom.safe.setAnchorHref, not with
361 // element.setAttribute.
362 assertEquals('http://google.com', element.href);
363 assertEquals('_blank', attrs['target']);
364 assertEquals('noreferrer', attrs['rel']);
365
366 // Click event.
367 assertNotNull(dispatchedEvent);
368 assertEquals('click', dispatchedEvent.type);
369 }
370
371
372 function testOpenNoReferrerEscapesUrl() {
373 var documentWriteHtml;
374 var mockNewWin = {};
375 mockNewWin.document = {
376 write: function(html) { documentWriteHtml = html; },
377 close: function() {}
378 };
379 var mockWin = {open: function() { return mockNewWin; }};
380 goog.window.open('https://hello&world', {noreferrer: true}, mockWin);
381 assertRegExp(
382 'Does not contain expected HTML-escaped string: ' + documentWriteHtml,
383 /hello&amp;world/, documentWriteHtml);
384 }
385
386 function testOpenNewWindowNoopener() {
387 newWin = goog.window.open(
388 REDIRECT_URL_PREFIX + 'theBest', {'target': '_blank', 'noopener': true});
389
390 // This mode cannot return a new window.
391 assertNotNull(newWin);
392 assertNotEquals(undefined, newWin.document);
393 assertNull(newWin.opener);
394
395 return waitForTestWindow(newWin).then(function(win) {
396 verifyWindow(win, false, 'theBest');
397 });
398 }