Debian Codegraph @

closure-library/closure/goog/history/history.js

raw
1 // Copyright 2007 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 /**
16 * @fileoverview Browser history stack management class.
17 *
18 * The goog.History object allows a page to create history state without leaving
19 * the current document. This allows users to, for example, hit the browser's
20 * back button without leaving the current page.
21 *
22 * The history object can be instantiated in one of two modes. In user visible
23 * mode, the current history state is shown in the browser address bar as a
24 * document location fragment (the portion of the URL after the '#'). These
25 * addresses can be bookmarked, copied and pasted into another browser, and
26 * modified directly by the user like any other URL.
27 *
28 * If the history object is created in invisible mode, the user can still
29 * affect the state using the browser forward and back buttons, but the current
30 * state is not displayed in the browser address bar. These states are not
31 * bookmarkable or editable.
32 *
33 * It is possible to use both types of history object on the same page, but not
34 * currently recommended due to browser deficiencies.
35 *
36 * Tested to work in:
37 * <ul>
38 * <li>Firefox 1.0-4.0
39 * <li>Internet Explorer 5.5-9.0
40 * <li>Opera 9+
41 * <li>Safari 4+
42 * </ul>
43 *
44 * @author [email protected] (Shawn Brenneman)
45 * @see ../demos/history1.html
46 * @see ../demos/history2.html
47 */
48
49 /* Some browser specific implementation notes:
50 *
51 * Firefox (through version 2.0.0.1):
52 *
53 * Ideally, navigating inside the hidden iframe could be done using
54 * about:blank#state instead of a real page on the server. Setting the hash on
55 * about:blank creates history entries, but the hash is not recorded and is lost
56 * when the user hits the back button. This is true in Opera as well. A blank
57 * HTML page must be provided for invisible states to be recorded in the iframe
58 * hash.
59 *
60 * After leaving the page with the History object and returning to it (by
61 * hitting the back button from another site), the last state of the iframe is
62 * overwritten. The most recent state is saved in a hidden input field so the
63 * previous state can be restored.
64 *
65 * Firefox does not store the previous value of dynamically generated input
66 * elements. To save the state, the hidden element must be in the HTML document,
67 * either in the original source or added with document.write. If a reference
68 * to the input element is not provided as a constructor argument, then the
69 * history object creates one using document.write, in which case the history
70 * object must be created from a script in the body element of the page.
71 *
72 * Manually editing the address field to a different hash link prevents further
73 * updates to the address bar. The page continues to work as normal, but the
74 * address shown will be incorrect until the page is reloaded.
75 *
76 * NOTE(user): It should be noted that Firefox will URL encode any non-regular
77 * ascii character, along with |space|, ", <, and >, when added to the fragment.
78 * If you expect these characters in your tokens you should consider that
79 * setToken('<b>') would result in the history fragment "%3Cb%3E", and
80 * "esp&eacute;re" would show "esp%E8re". (IE allows unicode characters in the
81 * fragment)
82 *
83 * TODO(user): Should we encapsulate this escaping into the API for visible
84 * history and encode all characters that aren't supported by Firefox? It also
85 * needs to be optional so apps can elect to handle the escaping themselves.
86 *
87 *
88 * Internet Explorer (through version 7.0):
89 *
90 * IE does not modify the history stack when the document fragment is changed.
91 * We create history entries instead by using document.open and document.write
92 * into a hidden iframe.
93 *
94 * IE destroys the history stack when navigating from /foo.html#someFragment to
95 * /foo.html. The workaround is to always append the # to the URL. This is
96 * somewhat unfortunate when loading the page without any # specified, because
97 * a second "click" sound will play on load as the fragment is automatically
98 * appended. If the hash is always present, this can be avoided.
99 *
100 * Manually editing the hash in the address bar in IE6 and then hitting the back
101 * button can replace the page with a blank page. This is a Bad User Experience,
102 * but probably not preventable.
103 *
104 * IE also has a bug when the page is loaded via a server redirect, setting
105 * a new hash value on the window location will force a page reload. This will
106 * happen the first time setToken is called with a new token. The only known
107 * workaround is to force a client reload early, for example by setting
108 * window.location.hash = window.location.hash, which will otherwise be a no-op.
109 *
110 * Internet Explorer 8.0, Webkit 532.1 and Gecko 1.9.2:
111 *
112 * IE8 has introduced the support to the HTML5 onhashchange event, which means
113 * we don't have to do any polling to detect fragment changes. Chrome and
114 * Firefox have added it on their newer builds, wekbit 532.1 and gecko 1.9.2.
115 * http://www.w3.org/TR/html5/history.html
116 * NOTE(goto): it is important to note that the document needs to have the
117 * <!DOCTYPE html> tag to enable the IE8 HTML5 mode. If the tag is not present,
118 * IE8 will enter IE7 compatibility mode (which can also be enabled manually).
119 *
120 * Opera (through version 9.02):
121 *
122 * Navigating through pages at a rate faster than some threshold causes Opera
123 * to cancel all outstanding timeouts and intervals, including the location
124 * polling loop. Since this condition cannot be detected, common input events
125 * are captured to cause the loop to restart.
126 *
127 * location.replace is adding a history entry inside setHash_, despite
128 * documentation that suggests it should not.
129 *
130 *
131 * Safari (through version 2.0.4):
132 *
133 * After hitting the back button, the location.hash property is no longer
134 * readable from JavaScript. This is fixed in later WebKit builds, but not in
135 * currently shipping Safari. For now, the only recourse is to disable history
136 * states in Safari. Pages are still navigable via the History object, but the
137 * back button cannot restore previous states.
138 *
139 * Safari sets history states on navigation to a hashlink, but doesn't allow
140 * polling of the hash, so following actual anchor links in the page will create
141 * useless history entries. Using location.replace does not seem to prevent
142 * this. Not a terribly good user experience, but fixed in later Webkits.
143 *
144 *
145 * WebKit (nightly version 420+):
146 *
147 * This almost works. Returning to a page with an invisible history object does
148 * not restore the old state, however, and there is no pageshow event that fires
149 * in this browser. Holding off on finding a solution for now.
150 *
151 *
152 * HTML5 capable browsers (Firefox 4, Chrome, Safari 5)
153 *
154 * No known issues. The goog.history.Html5History class provides a simpler
155 * implementation more suitable for recent browsers. These implementations
156 * should be merged so the history class automatically invokes the correct
157 * implementation.
158 */
159
160
161 goog.provide('goog.History');
162 goog.provide('goog.History.Event');
163 goog.provide('goog.History.EventType');
164
165 goog.require('goog.Timer');
166 goog.require('goog.asserts');
167 goog.require('goog.dom');
168 goog.require('goog.dom.InputType');
169 goog.require('goog.dom.safe');
170 /** @suppress {extraRequire} */
171 goog.require('goog.events.Event');
172 goog.require('goog.events.EventHandler');
173 goog.require('goog.events.EventTarget');
174 goog.require('goog.events.EventType');
175 goog.require('goog.history.Event');
176 goog.require('goog.history.EventType');
177 goog.require('goog.html.SafeHtml');
178 goog.require('goog.html.TrustedResourceUrl');
179 goog.require('goog.html.uncheckedconversions');
180 goog.require('goog.labs.userAgent.device');
181 goog.require('goog.memoize');
182 goog.require('goog.string');
183 goog.require('goog.string.Const');
184 goog.require('goog.userAgent');
185
186
187
188 /**
189 * A history management object. Can be instantiated in user-visible mode (uses
190 * the address fragment to manage state) or in hidden mode. This object should
191 * be created from a script in the document body before the document has
192 * finished loading.
193 *
194 * To store the hidden states in browsers other than IE, a hidden iframe is
195 * used. It must point to a valid html page on the same domain (which can and
196 * probably should be blank.)
197 *
198 * Sample instantiation and usage:
199 *
200 * <pre>
201 * // Instantiate history to use the address bar for state.
202 * var h = new goog.History();
203 * goog.events.listen(h, goog.history.EventType.NAVIGATE, navCallback);
204 * h.setEnabled(true);
205 *
206 * // Any changes to the location hash will call the following function.
207 * function navCallback(e) {
208 * alert('Navigated to state "' + e.token + '"');
209 * }
210 *
211 * // The history token can also be set from code directly.
212 * h.setToken('foo');
213 * </pre>
214 *
215 * @param {boolean=} opt_invisible True to use hidden history states instead of
216 * the user-visible location hash.
217 * @param {!goog.html.TrustedResourceUrl=} opt_blankPageUrl A URL to a
218 * blank page on the same server. Required if opt_invisible is true.
219 * This URL is also used as the src for the iframe used to track history
220 * state in IE (if not specified the iframe is not given a src attribute).
221 * Access is Denied error may occur in IE7 if the window's URL's scheme
222 * is https, and this URL is not specified.
223 * @param {HTMLInputElement=} opt_input The hidden input element to be used to
224 * store the history token. If not provided, a hidden input element will
225 * be created using document.write.
226 * @param {HTMLIFrameElement=} opt_iframe The hidden iframe that will be used by
227 * IE for pushing history state changes, or by all browsers if opt_invisible
228 * is true. If not provided, a hidden iframe element will be created using
229 * document.write.
230 * @constructor
231 * @extends {goog.events.EventTarget}
232 */
233 goog.History = function(
234 opt_invisible, opt_blankPageUrl, opt_input, opt_iframe) {
235 goog.events.EventTarget.call(this);
236
237 if (opt_invisible && !opt_blankPageUrl) {
238 throw new Error(
239 'Can\'t use invisible history without providing a blank page.');
240 }
241
242 var input;
243 if (opt_input) {
244 input = opt_input;
245 } else {
246 var inputId = 'history_state' + goog.History.historyCount_;
247 var inputHtml = goog.html.SafeHtml.create('input', {
248 type: goog.dom.InputType.TEXT,
249 name: inputId,
250 id: inputId,
251 style: goog.string.Const.from('display:none')
252 });
253 goog.dom.safe.documentWrite(document, inputHtml);
254 input = goog.dom.getElement(inputId);
255 }
256
257 /**
258 * An input element that stores the current iframe state. Used to restore
259 * the state when returning to the page on non-IE browsers.
260 * @type {HTMLInputElement}
261 * @private
262 */
263 this.hiddenInput_ = /** @type {HTMLInputElement} */ (input);
264
265 /**
266 * The window whose location contains the history token fragment. This is
267 * the window that contains the hidden input. It's typically the top window.
268 * It is not necessarily the same window that the js code is loaded in.
269 * @type {Window}
270 * @private
271 */
272 this.window_ = opt_input ?
273 goog.dom.getWindow(goog.dom.getOwnerDocument(opt_input)) :
274 window;
275
276 /**
277 * The base URL for the hidden iframe. Must refer to a document in the
278 * same domain as the main page.
279 * @type {!goog.html.TrustedResourceUrl|undefined}
280 * @private
281 */
282 this.iframeSrc_ = opt_blankPageUrl;
283
284 if (goog.userAgent.IE && !opt_blankPageUrl) {
285 if (window.location.protocol == 'https') {
286 this.iframeSrc_ = goog.html.TrustedResourceUrl.fromConstant(
287 goog.string.Const.from('https:///'));
288 } else {
289 this.iframeSrc_ = goog.html.TrustedResourceUrl.fromConstant(
290 goog.string.Const.from('javascript:""'));
291 }
292 }
293
294 /**
295 * A timer for polling the current history state for changes.
296 * @type {goog.Timer}
297 * @private
298 */
299 this.timer_ = new goog.Timer(goog.History.PollingType.NORMAL);
300 this.registerDisposable(this.timer_);
301
302 /**
303 * True if the state tokens are displayed in the address bar, false for hidden
304 * history states.
305 * @type {boolean}
306 * @private
307 */
308 this.userVisible_ = !opt_invisible;
309
310 /**
311 * An object to keep track of the history event listeners.
312 * @type {goog.events.EventHandler<!goog.History>}
313 * @private
314 */
315 this.eventHandler_ = new goog.events.EventHandler(this);
316
317 if (opt_invisible || goog.History.LEGACY_IE) {
318 var iframe;
319 if (opt_iframe) {
320 iframe = opt_iframe;
321 } else {
322 var iframeId = 'history_iframe' + goog.History.historyCount_;
323 // Using a "sandbox" attribute on the iframe might be possible, but
324 // this HTML didn't initially have it and when it was refactored
325 // to SafeHtml it was kept without it.
326 var iframeHtml = goog.html.SafeHtml.createIframe(this.iframeSrc_, null, {
327 id: iframeId,
328 style: goog.string.Const.from('display:none'),
329 sandbox: undefined
330 });
331 goog.dom.safe.documentWrite(document, iframeHtml);
332 iframe = goog.dom.getElement(iframeId);
333 }
334
335 /**
336 * Internet Explorer uses a hidden iframe for all history changes. Other
337 * browsers use the iframe only for pushing invisible states.
338 * @type {HTMLIFrameElement}
339 * @private
340 */
341 this.iframe_ = /** @type {HTMLIFrameElement} */ (iframe);
342
343 /**
344 * Whether the hidden iframe has had a document written to it yet in this
345 * session.
346 * @type {boolean}
347 * @private
348 */
349 this.unsetIframe_ = true;
350 }
351
352 if (goog.History.LEGACY_IE) {
353 // IE relies on the hidden input to restore the history state from previous
354 // sessions, but input values are only restored after window.onload. Set up
355 // a callback to poll the value after the onload event.
356 this.eventHandler_.listen(
357 this.window_, goog.events.EventType.LOAD, this.onDocumentLoaded);
358
359 /**
360 * IE-only variable for determining if the document has loaded.
361 * @type {boolean}
362 * @protected
363 */
364 this.documentLoaded = false;
365
366 /**
367 * IE-only variable for storing whether the history object should be enabled
368 * once the document finishes loading.
369 * @type {boolean}
370 * @private
371 */
372 this.shouldEnable_ = false;
373 }
374
375 // Set the initial history state.
376 if (this.userVisible_) {
377 this.setHash_(this.getToken(), true);
378 } else {
379 this.setIframeToken_(this.hiddenInput_.value);
380 }
381
382 goog.History.historyCount_++;
383 };
384 goog.inherits(goog.History, goog.events.EventTarget);
385
386
387 /**
388 * Status of when the object is active and dispatching events.
389 * @type {boolean}
390 * @private
391 */
392 goog.History.prototype.enabled_ = false;
393
394
395 /**
396 * Whether the object is performing polling with longer intervals. This can
397 * occur for instance when setting the location of the iframe when in invisible
398 * mode and the server that is hosting the blank html page is down. In FF, this
399 * will cause the location of the iframe to no longer be accessible, with
400 * permision denied exceptions being thrown on every access of the history
401 * token. When this occurs, the polling interval is elongated. This causes
402 * exceptions to be thrown at a lesser rate while allowing for the history
403 * object to resurrect itself when the html page becomes accessible.
404 * @type {boolean}
405 * @private
406 */
407 goog.History.prototype.longerPolling_ = false;
408
409
410 /**
411 * The last token set by the history object, used to poll for changes.
412 * @type {?string}
413 * @private
414 */
415 goog.History.prototype.lastToken_ = null;
416
417
418 /**
419 * Whether the browser supports HTML5 history management's onhashchange event.
420 * {@link http://www.w3.org/TR/html5/history.html}. IE 9 in compatibility mode
421 * indicates that onhashchange is in window, but testing reveals the event
422 * isn't actually fired.
423 * @return {boolean} Whether onhashchange is supported.
424 */
425 goog.History.isOnHashChangeSupported = goog.memoize(function() {
426 return goog.userAgent.IE ? goog.userAgent.isDocumentModeOrHigher(8) :
427 'onhashchange' in goog.global;
428 });
429
430
431 /**
432 * Whether the current browser is Internet Explorer prior to version 8. Many IE
433 * specific workarounds developed before version 8 are unnecessary in more
434 * current versions.
435 * @type {boolean}
436 */
437 goog.History.LEGACY_IE =
438 goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(8);
439
440
441 /**
442 * Whether the browser always requires the hash to be present. Internet Explorer
443 * before version 8 will reload the HTML page if the hash is omitted.
444 * @type {boolean}
445 */
446 goog.History.HASH_ALWAYS_REQUIRED = goog.History.LEGACY_IE;
447
448
449 /**
450 * If not null, polling in the user invisible mode will be disabled until this
451 * token is seen. This is used to prevent a race condition where the iframe
452 * hangs temporarily while the location is changed.
453 * @type {?string}
454 * @private
455 */
456 goog.History.prototype.lockedToken_ = null;
457
458
459 /** @override */
460 goog.History.prototype.disposeInternal = function() {
461 goog.History.superClass_.disposeInternal.call(this);
462 this.eventHandler_.dispose();
463 this.setEnabled(false);
464 };
465
466
467 /**
468 * Starts or stops the History polling loop. When enabled, the History object
469 * will immediately fire an event for the current location. The caller can set
470 * up event listeners between the call to the constructor and the call to
471 * setEnabled.
472 *
473 * On IE, actual startup may be delayed until the iframe and hidden input
474 * element have been loaded and can be polled. This behavior is transparent to
475 * the caller.
476 *
477 * @param {boolean} enable Whether to enable the history polling loop.
478 */
479 goog.History.prototype.setEnabled = function(enable) {
480
481 if (enable == this.enabled_) {
482 return;
483 }
484
485 if (goog.History.LEGACY_IE && !this.documentLoaded) {
486 // Wait until the document has actually loaded before enabling the
487 // object or any saved state from a previous session will be lost.
488 this.shouldEnable_ = enable;
489 return;
490 }
491
492 if (enable) {
493 if (goog.userAgent.OPERA) {
494 // Capture events for common user input so we can restart the timer in
495 // Opera if it fails. Yes, this is distasteful. See operaDefibrillator_.
496 this.eventHandler_.listen(
497 this.window_.document, goog.History.INPUT_EVENTS_,
498 this.operaDefibrillator_);
499 } else if (goog.userAgent.GECKO) {
500 // Firefox will not restore the correct state after navigating away from
501 // and then back to the page with the history object. This can be fixed
502 // by restarting the history object on the pageshow event.
503 this.eventHandler_.listen(this.window_, 'pageshow', this.onShow_);
504 }
505
506 // TODO(user): make HTML5 and invisible history work by listening to the
507 // iframe # changes instead of the window.
508 if (goog.History.isOnHashChangeSupported() && this.userVisible_) {
509 this.eventHandler_.listen(
510 this.window_, goog.events.EventType.HASHCHANGE, this.onHashChange_);
511 this.enabled_ = true;
512 this.dispatchEvent(new goog.history.Event(this.getToken(), false));
513 } else if (
514 !(goog.userAgent.IE && !goog.labs.userAgent.device.isMobile()) ||
515 this.documentLoaded) {
516 // Start dispatching history events if all necessary loading has
517 // completed (always true for browsers other than IE.)
518 this.eventHandler_.listen(
519 this.timer_, goog.Timer.TICK, goog.bind(this.check_, this, true));
520
521 this.enabled_ = true;
522
523 // Initialize last token at startup except on IE < 8, where the last token
524 // must only be set in conjunction with IFRAME updates, or the IFRAME will
525 // start out of sync and remove any pre-existing URI fragment.
526 if (!goog.History.LEGACY_IE) {
527 this.lastToken_ = this.getToken();
528 this.dispatchEvent(new goog.history.Event(this.getToken(), false));
529 }
530
531 this.timer_.start();
532 }
533
534 } else {
535 this.enabled_ = false;
536 this.eventHandler_.removeAll();
537 this.timer_.stop();
538 }
539 };
540
541
542 /**
543 * Callback for the window onload event in IE. This is necessary to read the
544 * value of the hidden input after restoring a history session. The value of
545 * input elements is not viewable until after window onload for some reason (the
546 * iframe state is similarly unavailable during the loading phase.) If
547 * setEnabled is called before the iframe has completed loading, the history
548 * object will actually be enabled at this point.
549 * @protected
550 */
551 goog.History.prototype.onDocumentLoaded = function() {
552 this.documentLoaded = true;
553
554 if (this.hiddenInput_.value) {
555 // Any saved value in the hidden input can only be read after the document
556 // has been loaded due to an IE limitation. Restore the previous state if
557 // it has been set.
558 this.setIframeToken_(this.hiddenInput_.value, true);
559 }
560
561 this.setEnabled(this.shouldEnable_);
562 };
563
564
565 /**
566 * Handler for the Gecko pageshow event. Restarts the history object so that the
567 * correct state can be restored in the hash or iframe.
568 * @param {goog.events.BrowserEvent} e The browser event.
569 * @private
570 */
571 goog.History.prototype.onShow_ = function(e) {
572 // NOTE(user): persisted is a property passed in the pageshow event that
573 // indicates whether the page is being persisted from the cache or is being
574 // loaded for the first time.
575 if (e.getBrowserEvent()['persisted']) {
576 this.setEnabled(false);
577 this.setEnabled(true);
578 }
579 };
580
581
582 /**
583 * Handles HTML5 onhashchange events on browsers where it is supported.
584 * This is very similar to {@link #check_}, except that it is not executed
585 * continuously. It is only used when
586 * {@code goog.History.isOnHashChangeSupported()} is true.
587 * @param {goog.events.BrowserEvent} e The browser event.
588 * @private
589 */
590 goog.History.prototype.onHashChange_ = function(e) {
591 var hash = this.getLocationFragment_(this.window_);
592 if (hash != this.lastToken_) {
593 this.update_(hash, true);
594 }
595 };
596
597
598 /**
599 * @return {string} The current token.
600 */
601 goog.History.prototype.getToken = function() {
602 if (this.lockedToken_ != null) {
603 return this.lockedToken_;
604 } else if (this.userVisible_) {
605 return this.getLocationFragment_(this.window_);
606 } else {
607 return this.getIframeToken_() || '';
608 }
609 };
610
611
612 /**
613 * Sets the history state. When user visible states are used, the URL fragment
614 * will be set to the provided token. Sometimes it is necessary to set the
615 * history token before the document title has changed, in this case IE's
616 * history drop down can be out of sync with the token. To get around this
617 * problem, the app can pass in a title to use with the hidden iframe.
618 * @param {string} token The history state identifier.
619 * @param {string=} opt_title Optional title used when setting the hidden iframe
620 * title in IE.
621 */
622 goog.History.prototype.setToken = function(token, opt_title) {
623 this.setHistoryState_(token, false, opt_title);
624 };
625
626
627 /**
628 * Replaces the current history state without affecting the rest of the history
629 * stack.
630 * @param {string} token The history state identifier.
631 * @param {string=} opt_title Optional title used when setting the hidden iframe
632 * title in IE.
633 */
634 goog.History.prototype.replaceToken = function(token, opt_title) {
635 this.setHistoryState_(token, true, opt_title);
636 };
637
638
639 /**
640 * Gets the location fragment for the current URL. We don't use location.hash
641 * directly as the browser helpfully urlDecodes the string for us which can
642 * corrupt the tokens. For example, if we want to store: label/%2Froot it would
643 * be returned as label//root.
644 * @param {Window} win The window object to use.
645 * @return {string} The fragment.
646 * @private
647 */
648 goog.History.prototype.getLocationFragment_ = function(win) {
649 var href = win.location.href;
650 var index = href.indexOf('#');
651 return index < 0 ? '' : href.substring(index + 1);
652 };
653
654
655 /**
656 * Sets the history state. When user visible states are used, the URL fragment
657 * will be set to the provided token. Setting opt_replace to true will cause the
658 * navigation to occur, but will replace the current history entry without
659 * affecting the length of the stack.
660 *
661 * @param {string} token The history state identifier.
662 * @param {boolean} replace Set to replace the current history entry instead of
663 * appending a new history state.
664 * @param {string=} opt_title Optional title used when setting the hidden iframe
665 * title in IE.
666 * @private
667 */
668 goog.History.prototype.setHistoryState_ = function(token, replace, opt_title) {
669 if (this.getToken() != token) {
670 if (this.userVisible_) {
671 this.setHash_(token, replace);
672
673 if (!goog.History.isOnHashChangeSupported()) {
674 if (goog.userAgent.IE && !goog.labs.userAgent.device.isMobile()) {
675 // IE must save state using the iframe.
676 this.setIframeToken_(token, replace, opt_title);
677 }
678 }
679
680 // This condition needs to be called even if
681 // goog.History.isOnHashChangeSupported() is true so the NAVIGATE event
682 // fires sychronously.
683 if (this.enabled_) {
684 this.check_(false);
685 }
686 } else {
687 // Fire the event immediately so that setting history is synchronous, but
688 // set a suspendToken so that polling doesn't trigger a 'back'.
689 this.setIframeToken_(token, replace);
690 this.lockedToken_ = this.lastToken_ = this.hiddenInput_.value = token;
691 this.dispatchEvent(new goog.history.Event(token, false));
692 }
693 }
694 };
695
696
697 /**
698 * Sets or replaces the URL fragment. The token does not need to be URL encoded
699 * according to the URL specification, though certain characters (like newline)
700 * are automatically stripped.
701 *
702 * If opt_replace is not set, non-IE browsers will append a new entry to the
703 * history list. Setting the hash does not affect the history stack in IE
704 * (unless there is a pre-existing named anchor for that hash.)
705 *
706 * Older versions of Webkit cannot query the location hash, but it still can be
707 * set. If we detect one of these versions, always replace instead of creating
708 * new history entries.
709 *
710 * window.location.replace replaces the current state from the history stack.
711 * http://www.whatwg.org/specs/web-apps/current-work/#dom-location-replace
712 * http://www.whatwg.org/specs/web-apps/current-work/#replacement-enabled
713 *
714 * @param {string} token The new string to set.
715 * @param {boolean=} opt_replace Set to true to replace the current token
716 * without appending a history entry.
717 * @private
718 */
719 goog.History.prototype.setHash_ = function(token, opt_replace) {
720 // If the page uses a BASE element, setting location.hash directly will
721 // navigate away from the current document. Also, the original URL path may
722 // possibly change from HTML5 history pushState. To account for these, the
723 // full path is always specified.
724 var loc = this.window_.location;
725 var url = loc.href.split('#')[0];
726
727 // If a hash has already been set, then removing it programmatically will
728 // reload the page. Once there is a hash, we won't remove it.
729 var hasHash = goog.string.contains(loc.href, '#');
730
731 if (goog.History.HASH_ALWAYS_REQUIRED || hasHash || token) {
732 url += '#' + token;
733 }
734
735 if (url != loc.href) {
736 if (opt_replace) {
737 loc.replace(url);
738 } else {
739 goog.dom.safe.setLocationHref(
740 loc,
741 goog.html.uncheckedconversions
742 .safeUrlFromStringKnownToSatisfyTypeContract(
743 goog.string.Const.from('URL taken from location.href.'),
744 url));
745 }
746 }
747 };
748
749
750 /**
751 * Sets the hidden iframe state. On IE, this is accomplished by writing a new
752 * document into the iframe. In Firefox, the iframe's URL fragment stores the
753 * state instead.
754 *
755 * Older versions of webkit cannot set the iframe, so ignore those browsers.
756 *
757 * @param {string} token The new string to set.
758 * @param {boolean=} opt_replace Set to true to replace the current iframe state
759 * without appending a new history entry.
760 * @param {string=} opt_title Optional title used when setting the hidden iframe
761 * title in IE.
762 * @private
763 */
764 goog.History.prototype.setIframeToken_ = function(
765 token, opt_replace, opt_title) {
766 if (this.unsetIframe_ || token != this.getIframeToken_()) {
767 this.unsetIframe_ = false;
768 token = goog.string.urlEncode(token);
769
770 if (goog.userAgent.IE) {
771 // Caching the iframe document results in document permission errors after
772 // leaving the page and returning. Access it anew each time instead.
773 var doc = goog.dom.getFrameContentDocument(this.iframe_);
774
775 doc.open('text/html', opt_replace ? 'replace' : undefined);
776 var iframeSourceHtml = goog.html.SafeHtml.concat(
777 goog.html.SafeHtml.create(
778 'title', {}, (opt_title || this.window_.document.title)),
779 goog.html.SafeHtml.create('body', {}, token));
780 goog.dom.safe.documentWrite(doc, iframeSourceHtml);
781 doc.close();
782 } else {
783 goog.asserts.assertInstanceof(
784 this.iframeSrc_, goog.html.TrustedResourceUrl,
785 'this.iframeSrc_ must be set on calls to setIframeToken_');
786 var url =
787 goog.html.TrustedResourceUrl.unwrap(
788 /** @type {!goog.html.TrustedResourceUrl} */ (this.iframeSrc_)) +
789 '#' + token;
790
791 // In Safari, it is possible for the contentWindow of the iframe to not
792 // be present when the page is loading after a reload.
793 var contentWindow = this.iframe_.contentWindow;
794 if (contentWindow) {
795 if (opt_replace) {
796 contentWindow.location.replace(url);
797 } else {
798 goog.dom.safe.setLocationHref(contentWindow.location, url);
799 }
800 }
801 }
802 }
803 };
804
805
806 /**
807 * Return the current state string from the hidden iframe. On internet explorer,
808 * this is stored as a string in the document body. Other browsers use the
809 * location hash of the hidden iframe.
810 *
811 * Older versions of webkit cannot access the iframe location, so always return
812 * null in that case.
813 *
814 * @return {?string} The state token saved in the iframe (possibly null if the
815 * iframe has never loaded.).
816 * @private
817 */
818 goog.History.prototype.getIframeToken_ = function() {
819 if (goog.userAgent.IE) {
820 var doc = goog.dom.getFrameContentDocument(this.iframe_);
821 return doc.body ? goog.string.urlDecode(doc.body.innerHTML) : null;
822 } else {
823 // In Safari, it is possible for the contentWindow of the iframe to not
824 // be present when the page is loading after a reload.
825 var contentWindow = this.iframe_.contentWindow;
826 if (contentWindow) {
827 var hash;
828
829 try {
830 // Iframe tokens are urlEncoded
831 hash = goog.string.urlDecode(this.getLocationFragment_(contentWindow));
832 } catch (e) {
833 // An exception will be thrown if the location of the iframe can not be
834 // accessed (permission denied). This can occur in FF if the the server
835 // that is hosting the blank html page goes down and then a new history
836 // token is set. The iframe will navigate to an error page, and the
837 // location of the iframe can no longer be accessed. Due to the polling,
838 // this will cause constant exceptions to be thrown. In this case,
839 // we enable longer polling. We do not have to attempt to reset the
840 // iframe token because (a) we already fired the NAVIGATE event when
841 // setting the token, (b) we can rely on the locked token for current
842 // state, and (c) the token is still in the history and
843 // accesible on forward/back.
844 if (!this.longerPolling_) {
845 this.setLongerPolling_(true);
846 }
847
848 return null;
849 }
850
851 // There was no exception when getting the hash so turn off longer polling
852 // if it is on.
853 if (this.longerPolling_) {
854 this.setLongerPolling_(false);
855 }
856
857 return hash || null;
858 } else {
859 return null;
860 }
861 }
862 };
863
864
865 /**
866 * Checks the state of the document fragment and the iframe title to detect
867 * navigation changes. If {@code goog.HistoryisOnHashChangeSupported()} is
868 * {@code false}, then this runs approximately twenty times per second.
869 * @param {boolean} isNavigation True if the event was initiated by a browser
870 * action, false if it was caused by a setToken call. See
871 * {@link goog.history.Event}.
872 * @private
873 */
874 goog.History.prototype.check_ = function(isNavigation) {
875 if (this.userVisible_) {
876 var hash = this.getLocationFragment_(this.window_);
877 if (hash != this.lastToken_) {
878 this.update_(hash, isNavigation);
879 }
880 }
881
882 // Old IE uses the iframe for both visible and non-visible versions.
883 if (!this.userVisible_ || goog.History.LEGACY_IE) {
884 var token = this.getIframeToken_() || '';
885 if (this.lockedToken_ == null || token == this.lockedToken_) {
886 this.lockedToken_ = null;
887 if (token != this.lastToken_) {
888 this.update_(token, isNavigation);
889 }
890 }
891 }
892 };
893
894
895 /**
896 * Updates the current history state with a given token. Called after a change
897 * to the location or the iframe state is detected by poll_.
898 *
899 * @param {string} token The new history state.
900 * @param {boolean} isNavigation True if the event was initiated by a browser
901 * action, false if it was caused by a setToken call. See
902 * {@link goog.history.Event}.
903 * @private
904 */
905 goog.History.prototype.update_ = function(token, isNavigation) {
906 this.lastToken_ = this.hiddenInput_.value = token;
907
908 if (this.userVisible_) {
909 if (goog.History.LEGACY_IE) {
910 this.setIframeToken_(token);
911 }
912
913 this.setHash_(token);
914 } else {
915 this.setIframeToken_(token);
916 }
917
918 this.dispatchEvent(new goog.history.Event(this.getToken(), isNavigation));
919 };
920
921
922 /**
923 * Sets if the history oject should use longer intervals when polling.
924 *
925 * @param {boolean} longerPolling Whether to enable longer polling.
926 * @private
927 */
928 goog.History.prototype.setLongerPolling_ = function(longerPolling) {
929 if (this.longerPolling_ != longerPolling) {
930 this.timer_.setInterval(
931 longerPolling ? goog.History.PollingType.LONG :
932 goog.History.PollingType.NORMAL);
933 }
934 this.longerPolling_ = longerPolling;
935 };
936
937
938 /**
939 * Opera cancels all outstanding timeouts and intervals after any rapid
940 * succession of navigation events, including the interval used to detect
941 * navigation events. This function restarts the interval so that navigation can
942 * continue. Ideally, only events which would be likely to cause a navigation
943 * change (mousedown and keydown) would be bound to this function. Since Opera
944 * seems to ignore keydown events while the alt key is pressed (such as
945 * alt-left or right arrow), this function is also bound to the much more
946 * frequent mousemove event. This way, when the update loop freezes, it will
947 * unstick itself as the user wiggles the mouse in frustration.
948 * @private
949 */
950 goog.History.prototype.operaDefibrillator_ = function() {
951 this.timer_.stop();
952 this.timer_.start();
953 };
954
955
956 /**
957 * List of user input event types registered in Opera to restart the history
958 * timer (@see goog.History#operaDefibrillator_).
959 * @type {Array<string>}
960 * @private
961 */
962 goog.History.INPUT_EVENTS_ = [
963 goog.events.EventType.MOUSEDOWN, goog.events.EventType.KEYDOWN,
964 goog.events.EventType.MOUSEMOVE
965 ];
966
967
968 /**
969 * Counter for the number of goog.History objects that have been instantiated.
970 * Used to create unique IDs.
971 * @type {number}
972 * @private
973 */
974 goog.History.historyCount_ = 0;
975
976
977 /**
978 * Types of polling. The values are in ms of the polling interval.
979 * @enum {number}
980 */
981 goog.History.PollingType = {
982 NORMAL: 150,
983 LONG: 10000
984 };
985
986
987 /**
988 * Constant for the history change event type.
989 * @enum {string}
990 * @deprecated Use goog.history.EventType.
991 */
992 goog.History.EventType = goog.history.EventType;
993
994
995
996 /**
997 * Constant for the history change event type.
998 * @constructor
999 * @deprecated Use goog.history.Event.
1000 * @final
1001 */
1002 goog.History.Event = goog.history.Event;