window.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. // Copyright 2006 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. * @fileoverview Utilities for window manipulation.
  16. */
  17. goog.provide('goog.window');
  18. goog.require('goog.dom.TagName');
  19. goog.require('goog.dom.safe');
  20. goog.require('goog.html.SafeUrl');
  21. goog.require('goog.html.uncheckedconversions');
  22. goog.require('goog.labs.userAgent.platform');
  23. goog.require('goog.string');
  24. goog.require('goog.string.Const');
  25. goog.require('goog.userAgent');
  26. /**
  27. * Default height for popup windows
  28. * @type {number}
  29. */
  30. goog.window.DEFAULT_POPUP_HEIGHT = 500;
  31. /**
  32. * Default width for popup windows
  33. * @type {number}
  34. */
  35. goog.window.DEFAULT_POPUP_WIDTH = 690;
  36. /**
  37. * Default target for popup windows
  38. * @type {string}
  39. */
  40. goog.window.DEFAULT_POPUP_TARGET = 'google_popup';
  41. /**
  42. * @return {!Window}
  43. * @suppress {checkTypes}
  44. * @private
  45. */
  46. goog.window.createFakeWindow_ = function() {
  47. return /** @type {!Window} */ ({});
  48. };
  49. /**
  50. * Opens a new window.
  51. *
  52. * @param {?goog.html.SafeUrl|string|?Object} linkRef If an Object with an 'href'
  53. * attribute (such as HTMLAnchorElement) is passed then the value of 'href'
  54. * is used, otherwise its toString method is called. Note that if a
  55. * string|Object is used, it will be sanitized with SafeUrl.sanitize().
  56. *
  57. * @param {?Object=} opt_options supports the following options:
  58. * 'target': (string) target (window name). If null, linkRef.target will
  59. * be used.
  60. * 'width': (number) window width.
  61. * 'height': (number) window height.
  62. * 'top': (number) distance from top of screen
  63. * 'left': (number) distance from left of screen
  64. * 'toolbar': (boolean) show toolbar
  65. * 'scrollbars': (boolean) show scrollbars
  66. * 'location': (boolean) show location
  67. * 'statusbar': (boolean) show statusbar
  68. * 'menubar': (boolean) show menubar
  69. * 'resizable': (boolean) resizable
  70. * 'noreferrer': (boolean) whether to attempt to remove the referrer header
  71. * from the request headers. Does this by opening a blank window that
  72. * then redirects to the target url, so users may see some flickering.
  73. *
  74. * @param {?Window=} opt_parentWin Parent window that should be used to open the
  75. * new window.
  76. *
  77. * @return {?Window} Returns the window object that was opened. This returns
  78. * null if a popup blocker prevented the window from being
  79. * opened. In case when a new window is opened in a different
  80. * browser sandbox (such as iOS standalone mode), the returned
  81. * object is a emulated Window object that functions as if
  82. * a cross-origin window has been opened.
  83. */
  84. goog.window.open = function(linkRef, opt_options, opt_parentWin) {
  85. if (!opt_options) {
  86. opt_options = {};
  87. }
  88. var parentWin = opt_parentWin || window;
  89. /** @type {!goog.html.SafeUrl} */
  90. var safeLinkRef;
  91. if (linkRef instanceof goog.html.SafeUrl) {
  92. safeLinkRef = linkRef;
  93. } else {
  94. // HTMLAnchorElement has a toString() method with the same behavior as
  95. // goog.Uri in all browsers except for Safari, which returns
  96. // '[object HTMLAnchorElement]'. We check for the href first, then
  97. // assume that it's a goog.Uri or String otherwise.
  98. var url =
  99. typeof linkRef.href != 'undefined' ? linkRef.href : String(linkRef);
  100. safeLinkRef = goog.html.SafeUrl.sanitize(url);
  101. }
  102. var target = opt_options.target || linkRef.target;
  103. var sb = [];
  104. for (var option in opt_options) {
  105. switch (option) {
  106. case 'width':
  107. case 'height':
  108. case 'top':
  109. case 'left':
  110. sb.push(option + '=' + opt_options[option]);
  111. break;
  112. case 'target':
  113. case 'noreferrer':
  114. break;
  115. default:
  116. sb.push(option + '=' + (opt_options[option] ? 1 : 0));
  117. }
  118. }
  119. var optionString = sb.join(',');
  120. var newWin;
  121. if (goog.labs.userAgent.platform.isIos() && parentWin.navigator &&
  122. parentWin.navigator['standalone'] && target && target != '_self') {
  123. // iOS in standalone mode disregards "target" in window.open and always
  124. // opens new URL in the same window. The workout around is to create an "A"
  125. // element and send a click event to it.
  126. // Notice that the "A" tag does NOT have to be added to the DOM.
  127. var a = /** @type {!HTMLAnchorElement} */
  128. (parentWin.document.createElement(String(goog.dom.TagName.A)));
  129. goog.dom.safe.setAnchorHref(a, safeLinkRef);
  130. a.setAttribute('target', target);
  131. if (opt_options['noreferrer']) {
  132. a.setAttribute('rel', 'noreferrer');
  133. }
  134. var click = document.createEvent('MouseEvent');
  135. click.initMouseEvent(
  136. 'click',
  137. true, // canBubble
  138. true, // cancelable
  139. parentWin,
  140. 1); // detail = mousebutton
  141. a.dispatchEvent(click);
  142. // New window is not available in this case. Instead, a fake Window object
  143. // is returned. In particular, it will have window.document undefined. In
  144. // general, it will appear to most of clients as a Window for a different
  145. // origin. Since iOS standalone web apps are run in their own sandbox, this
  146. // is the most appropriate return value.
  147. newWin = goog.window.createFakeWindow_();
  148. } else if (opt_options['noreferrer']) {
  149. // Use a meta-refresh to stop the referrer from being included in the
  150. // request headers. This seems to be the only cross-browser way to
  151. // remove the referrer. It also allows for the opener to be set to null
  152. // in the new window, thus disallowing the opened window from navigating
  153. // its opener.
  154. //
  155. // Detecting user agent and then using a different strategy per browser
  156. // would allow the referrer to leak in case of an incorrect/missing user
  157. // agent.
  158. //
  159. // Also note that we can't use goog.dom.safe.openInWindow here, as it
  160. // requires a goog.string.Const 'name' parameter, while we're using plain
  161. // strings here for target.
  162. newWin = parentWin.open('', target, optionString);
  163. var sanitizedLinkRef = goog.html.SafeUrl.unwrap(safeLinkRef);
  164. if (newWin) {
  165. if (goog.userAgent.EDGE_OR_IE) {
  166. // IE/EDGE can't parse the content attribute if the url contains
  167. // a semicolon. We can fix this by adding quotes around the url, but
  168. // then we can't parse quotes in the URL correctly. We take a
  169. // best-effort approach.
  170. //
  171. // If the URL has semicolons, wrap it in single quotes to protect
  172. // the semicolons.
  173. // If the URL has semicolons and single quotes, url-encode the single
  174. // quotes as well.
  175. //
  176. // This is imperfect. Notice that both ' and ; are reserved characters
  177. // in URIs, so this could do the wrong thing, but at least it will
  178. // do the wrong thing in only rare cases.
  179. // ugh.
  180. if (goog.string.contains(sanitizedLinkRef, ';')) {
  181. sanitizedLinkRef = "'" + sanitizedLinkRef.replace(/'/g, '%27') + "'";
  182. }
  183. }
  184. newWin.opener = null;
  185. // TODO(rjamet): Building proper SafeHtml with SafeHtml.createMetaRefresh
  186. // pulls in a lot of compiled code, which is composed of various unneeded
  187. // goog.html parts such as SafeStyle.create among others. So, for now,
  188. // keep the unchecked conversion until we figure out how to make the
  189. // dependencies of createSafeHtmlTagSecurityPrivateDoNotAccessOrElse less
  190. // heavy.
  191. var safeHtml =
  192. goog.html.uncheckedconversions
  193. .safeHtmlFromStringKnownToSatisfyTypeContract(
  194. goog.string.Const.from(
  195. 'b/12014412, meta tag with sanitized URL'),
  196. '<META HTTP-EQUIV="refresh" content="0; url=' +
  197. goog.string.htmlEscape(sanitizedLinkRef) + '">');
  198. goog.dom.safe.documentWrite(newWin.document, safeHtml);
  199. newWin.document.close();
  200. }
  201. } else {
  202. newWin = parentWin.open(
  203. goog.html.SafeUrl.unwrap(safeLinkRef), target, optionString);
  204. }
  205. // newWin is null if a popup blocker prevented the window open.
  206. return newWin;
  207. };
  208. /**
  209. * Opens a new window without any real content in it.
  210. *
  211. * This can be used to get around popup blockers if you need to open a window
  212. * in response to a user event, but need to do asynchronous work to determine
  213. * the URL to open, and then set the URL later.
  214. *
  215. * Example usage:
  216. *
  217. * var newWin = goog.window.openBlank('Loading...');
  218. * setTimeout(
  219. * function() {
  220. * newWin.location.href = 'http://www.google.com';
  221. * }, 100);
  222. *
  223. * @param {string=} opt_message String to show in the new window. This string
  224. * will be HTML-escaped to avoid XSS issues.
  225. * @param {?Object=} opt_options Options to open window with.
  226. * {@see goog.window.open for exact option semantics}.
  227. * @param {?Window=} opt_parentWin Parent window that should be used to open the
  228. * new window.
  229. * @return {?Window} Returns the window object that was opened. This returns
  230. * null if a popup blocker prevented the window from being
  231. * opened.
  232. */
  233. goog.window.openBlank = function(opt_message, opt_options, opt_parentWin) {
  234. // Open up a window with the loading message and nothing else.
  235. // This will be interpreted as HTML content type with a missing doctype
  236. // and html/body tags, but is otherwise acceptable.
  237. //
  238. // IMPORTANT: The order of escaping is crucial here in order to avoid XSS.
  239. // First, HTML-escaping is needed because the result of the JS expression
  240. // is evaluated as HTML. Second, JS-string escaping is needed; this avoids
  241. // \u escaping from inserting HTML tags and \ from escaping the final ".
  242. // Finally, URL percent-encoding is done with encodeURI(); this
  243. // avoids percent-encoding from bypassing HTML and JS escaping.
  244. //
  245. // Note: There are other ways the same result could be achieved but the
  246. // current behavior was preserved when this code was refactored to use
  247. // SafeUrl, in order to avoid breakage.
  248. var loadingMessage;
  249. if (!opt_message) {
  250. loadingMessage = '';
  251. } else {
  252. loadingMessage =
  253. goog.string.escapeString(goog.string.htmlEscape(opt_message));
  254. }
  255. var url = goog.html.uncheckedconversions
  256. .safeUrlFromStringKnownToSatisfyTypeContract(
  257. goog.string.Const.from(
  258. 'b/12014412, encoded string in javascript: URL'),
  259. 'javascript:"' + encodeURI(loadingMessage) + '"');
  260. return /** @type {?Window} */ (
  261. goog.window.open(url, opt_options, opt_parentWin));
  262. };
  263. /**
  264. * Raise a help popup window, defaulting to "Google standard" size and name.
  265. *
  266. * (If your project is using GXPs, consider using {@link PopUpLink.gxp}.)
  267. *
  268. * @param {?goog.html.SafeUrl|string|?Object} linkRef If an Object with an 'href'
  269. * attribute (such as HTMLAnchorElement) is passed then the value of 'href'
  270. * is used, otherwise otherwise its toString method is called. Note that
  271. * if a string|Object is used, it will be sanitized with SafeUrl.sanitize().
  272. *
  273. * @param {?Object=} opt_options Options to open window with.
  274. * {@see goog.window.open for exact option semantics}
  275. * Additional wrinkles to the options:
  276. * - if 'target' field is null, linkRef.target will be used. If *that's*
  277. * null, the default is "google_popup".
  278. * - if 'width' field is not specified, the default is 690.
  279. * - if 'height' field is not specified, the default is 500.
  280. *
  281. * @return {boolean} true if the window was not popped up, false if it was.
  282. */
  283. goog.window.popup = function(linkRef, opt_options) {
  284. if (!opt_options) {
  285. opt_options = {};
  286. }
  287. // set default properties
  288. opt_options['target'] = opt_options['target'] || linkRef['target'] ||
  289. goog.window.DEFAULT_POPUP_TARGET;
  290. opt_options['width'] =
  291. opt_options['width'] || goog.window.DEFAULT_POPUP_WIDTH;
  292. opt_options['height'] =
  293. opt_options['height'] || goog.window.DEFAULT_POPUP_HEIGHT;
  294. var newWin = goog.window.open(linkRef, opt_options);
  295. if (!newWin) {
  296. return true;
  297. }
  298. newWin.focus();
  299. return false;
  300. };