pdf_history.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. /* Copyright 2017 Mozilla Foundation
  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. /** @typedef {import("./event_utils").EventBus} EventBus */
  16. /** @typedef {import("./interfaces").IPDFLinkService} IPDFLinkService */
  17. import { isValidRotation, parseQueryString } from "./ui_utils.js";
  18. import { waitOnEventOrTimeout } from "./event_utils.js";
  19. // Heuristic value used when force-resetting `this._blockHashChange`.
  20. const HASH_CHANGE_TIMEOUT = 1000; // milliseconds
  21. // Heuristic value used when adding the current position to the browser history.
  22. const POSITION_UPDATED_THRESHOLD = 50;
  23. // Heuristic value used when adding a temporary position to the browser history.
  24. const UPDATE_VIEWAREA_TIMEOUT = 1000; // milliseconds
  25. /**
  26. * @typedef {Object} PDFHistoryOptions
  27. * @property {IPDFLinkService} linkService - The navigation/linking service.
  28. * @property {EventBus} eventBus - The application event bus.
  29. */
  30. /**
  31. * @typedef {Object} InitializeParameters
  32. * @property {string} fingerprint - The PDF document's unique fingerprint.
  33. * @property {boolean} [resetHistory] - Reset the browsing history.
  34. * @property {boolean} [updateUrl] - Attempt to update the document URL, with
  35. * the current hash, when pushing/replacing browser history entries.
  36. */
  37. /**
  38. * @typedef {Object} PushParameters
  39. * @property {string} [namedDest] - The named destination. If absent, a
  40. * stringified version of `explicitDest` is used.
  41. * @property {Array} explicitDest - The explicit destination array.
  42. * @property {number} pageNumber - The page to which the destination points.
  43. */
  44. function getCurrentHash() {
  45. return document.location.hash;
  46. }
  47. class PDFHistory {
  48. /**
  49. * @param {PDFHistoryOptions} options
  50. */
  51. constructor({ linkService, eventBus }) {
  52. this.linkService = linkService;
  53. this.eventBus = eventBus;
  54. this._initialized = false;
  55. this._fingerprint = "";
  56. this.reset();
  57. this._boundEvents = null;
  58. // Ensure that we don't miss a "pagesinit" event,
  59. // by registering the listener immediately.
  60. this.eventBus._on("pagesinit", () => {
  61. this._isPagesLoaded = false;
  62. this.eventBus._on(
  63. "pagesloaded",
  64. evt => {
  65. this._isPagesLoaded = !!evt.pagesCount;
  66. },
  67. { once: true }
  68. );
  69. });
  70. }
  71. /**
  72. * Initialize the history for the PDF document, using either the current
  73. * browser history entry or the document hash, whichever is present.
  74. * @param {InitializeParameters} params
  75. */
  76. initialize({ fingerprint, resetHistory = false, updateUrl = false }) {
  77. if (!fingerprint || typeof fingerprint !== "string") {
  78. console.error(
  79. 'PDFHistory.initialize: The "fingerprint" must be a non-empty string.'
  80. );
  81. return;
  82. }
  83. // Ensure that any old state is always reset upon initialization.
  84. if (this._initialized) {
  85. this.reset();
  86. }
  87. const reInitialized =
  88. this._fingerprint !== "" && this._fingerprint !== fingerprint;
  89. this._fingerprint = fingerprint;
  90. this._updateUrl = updateUrl === true;
  91. this._initialized = true;
  92. this._bindEvents();
  93. const state = window.history.state;
  94. this._popStateInProgress = false;
  95. this._blockHashChange = 0;
  96. this._currentHash = getCurrentHash();
  97. this._numPositionUpdates = 0;
  98. this._uid = this._maxUid = 0;
  99. this._destination = null;
  100. this._position = null;
  101. if (!this._isValidState(state, /* checkReload = */ true) || resetHistory) {
  102. const { hash, page, rotation } = this._parseCurrentHash(
  103. /* checkNameddest = */ true
  104. );
  105. if (!hash || reInitialized || resetHistory) {
  106. // Ensure that the browser history is reset on PDF document load.
  107. this._pushOrReplaceState(null, /* forceReplace = */ true);
  108. return;
  109. }
  110. // Ensure that the browser history is initialized correctly when
  111. // the document hash is present on PDF document load.
  112. this._pushOrReplaceState(
  113. { hash, page, rotation },
  114. /* forceReplace = */ true
  115. );
  116. return;
  117. }
  118. // The browser history contains a valid entry, ensure that the history is
  119. // initialized correctly on PDF document load.
  120. const destination = state.destination;
  121. this._updateInternalState(
  122. destination,
  123. state.uid,
  124. /* removeTemporary = */ true
  125. );
  126. if (destination.rotation !== undefined) {
  127. this._initialRotation = destination.rotation;
  128. }
  129. if (destination.dest) {
  130. this._initialBookmark = JSON.stringify(destination.dest);
  131. // If the history is updated, e.g. through the user changing the hash,
  132. // before the initial destination has become visible, then we do *not*
  133. // want to potentially add `this._position` to the browser history.
  134. this._destination.page = null;
  135. } else if (destination.hash) {
  136. this._initialBookmark = destination.hash;
  137. } else if (destination.page) {
  138. // Fallback case; shouldn't be necessary, but better safe than sorry.
  139. this._initialBookmark = `page=${destination.page}`;
  140. }
  141. }
  142. /**
  143. * Reset the current `PDFHistory` instance, and consequently prevent any
  144. * further updates and/or navigation of the browser history.
  145. */
  146. reset() {
  147. if (this._initialized) {
  148. this._pageHide(); // Simulate a 'pagehide' event when resetting.
  149. this._initialized = false;
  150. this._unbindEvents();
  151. }
  152. if (this._updateViewareaTimeout) {
  153. clearTimeout(this._updateViewareaTimeout);
  154. this._updateViewareaTimeout = null;
  155. }
  156. this._initialBookmark = null;
  157. this._initialRotation = null;
  158. }
  159. /**
  160. * Push an internal destination to the browser history.
  161. * @param {PushParameters}
  162. */
  163. push({ namedDest = null, explicitDest, pageNumber }) {
  164. if (!this._initialized) {
  165. return;
  166. }
  167. if (namedDest && typeof namedDest !== "string") {
  168. console.error(
  169. "PDFHistory.push: " +
  170. `"${namedDest}" is not a valid namedDest parameter.`
  171. );
  172. return;
  173. } else if (!Array.isArray(explicitDest)) {
  174. console.error(
  175. "PDFHistory.push: " +
  176. `"${explicitDest}" is not a valid explicitDest parameter.`
  177. );
  178. return;
  179. } else if (!this._isValidPage(pageNumber)) {
  180. // Allow an unset `pageNumber` if and only if the history is still empty;
  181. // please refer to the `this._destination.page = null;` comment above.
  182. if (pageNumber !== null || this._destination) {
  183. console.error(
  184. "PDFHistory.push: " +
  185. `"${pageNumber}" is not a valid pageNumber parameter.`
  186. );
  187. return;
  188. }
  189. }
  190. const hash = namedDest || JSON.stringify(explicitDest);
  191. if (!hash) {
  192. // The hash *should* never be undefined, but if that were to occur,
  193. // avoid any possible issues by not updating the browser history.
  194. return;
  195. }
  196. let forceReplace = false;
  197. if (
  198. this._destination &&
  199. (isDestHashesEqual(this._destination.hash, hash) ||
  200. isDestArraysEqual(this._destination.dest, explicitDest))
  201. ) {
  202. // When the new destination is identical to `this._destination`, and
  203. // its `page` is undefined, replace the current browser history entry.
  204. // NOTE: This can only occur if `this._destination` was set either:
  205. // - through the document hash being specified on load.
  206. // - through the user changing the hash of the document.
  207. if (this._destination.page) {
  208. return;
  209. }
  210. forceReplace = true;
  211. }
  212. if (this._popStateInProgress && !forceReplace) {
  213. return;
  214. }
  215. this._pushOrReplaceState(
  216. {
  217. dest: explicitDest,
  218. hash,
  219. page: pageNumber,
  220. rotation: this.linkService.rotation,
  221. },
  222. forceReplace
  223. );
  224. if (!this._popStateInProgress) {
  225. // Prevent the browser history from updating while the new destination is
  226. // being scrolled into view, to avoid potentially inconsistent state.
  227. this._popStateInProgress = true;
  228. // We defer the resetting of `this._popStateInProgress`, to account for
  229. // e.g. zooming occurring when the new destination is being navigated to.
  230. Promise.resolve().then(() => {
  231. this._popStateInProgress = false;
  232. });
  233. }
  234. }
  235. /**
  236. * Push a page to the browser history; generally the `push` method should be
  237. * used instead.
  238. * @param {number} pageNumber
  239. */
  240. pushPage(pageNumber) {
  241. if (!this._initialized) {
  242. return;
  243. }
  244. if (!this._isValidPage(pageNumber)) {
  245. console.error(
  246. `PDFHistory.pushPage: "${pageNumber}" is not a valid page number.`
  247. );
  248. return;
  249. }
  250. if (this._destination?.page === pageNumber) {
  251. // When the new page is identical to the one in `this._destination`, we
  252. // don't want to add a potential duplicate entry in the browser history.
  253. return;
  254. }
  255. if (this._popStateInProgress) {
  256. return;
  257. }
  258. this._pushOrReplaceState({
  259. // Simulate an internal destination, for `this._tryPushCurrentPosition`:
  260. dest: null,
  261. hash: `page=${pageNumber}`,
  262. page: pageNumber,
  263. rotation: this.linkService.rotation,
  264. });
  265. if (!this._popStateInProgress) {
  266. // Prevent the browser history from updating while the new page is
  267. // being scrolled into view, to avoid potentially inconsistent state.
  268. this._popStateInProgress = true;
  269. // We defer the resetting of `this._popStateInProgress`, to account for
  270. // e.g. zooming occurring when the new page is being navigated to.
  271. Promise.resolve().then(() => {
  272. this._popStateInProgress = false;
  273. });
  274. }
  275. }
  276. /**
  277. * Push the current position to the browser history.
  278. */
  279. pushCurrentPosition() {
  280. if (!this._initialized || this._popStateInProgress) {
  281. return;
  282. }
  283. this._tryPushCurrentPosition();
  284. }
  285. /**
  286. * Go back one step in the browser history.
  287. * NOTE: Avoids navigating away from the document, useful for "named actions".
  288. */
  289. back() {
  290. if (!this._initialized || this._popStateInProgress) {
  291. return;
  292. }
  293. const state = window.history.state;
  294. if (this._isValidState(state) && state.uid > 0) {
  295. window.history.back();
  296. }
  297. }
  298. /**
  299. * Go forward one step in the browser history.
  300. * NOTE: Avoids navigating away from the document, useful for "named actions".
  301. */
  302. forward() {
  303. if (!this._initialized || this._popStateInProgress) {
  304. return;
  305. }
  306. const state = window.history.state;
  307. if (this._isValidState(state) && state.uid < this._maxUid) {
  308. window.history.forward();
  309. }
  310. }
  311. /**
  312. * @type {boolean} Indicating if the user is currently moving through the
  313. * browser history, useful e.g. for skipping the next 'hashchange' event.
  314. */
  315. get popStateInProgress() {
  316. return (
  317. this._initialized &&
  318. (this._popStateInProgress || this._blockHashChange > 0)
  319. );
  320. }
  321. get initialBookmark() {
  322. return this._initialized ? this._initialBookmark : null;
  323. }
  324. get initialRotation() {
  325. return this._initialized ? this._initialRotation : null;
  326. }
  327. /**
  328. * @private
  329. */
  330. _pushOrReplaceState(destination, forceReplace = false) {
  331. const shouldReplace = forceReplace || !this._destination;
  332. const newState = {
  333. fingerprint: this._fingerprint,
  334. uid: shouldReplace ? this._uid : this._uid + 1,
  335. destination,
  336. };
  337. if (
  338. typeof PDFJSDev !== "undefined" &&
  339. PDFJSDev.test("CHROME") &&
  340. window.history.state?.chromecomState
  341. ) {
  342. // history.state.chromecomState is managed by chromecom.js.
  343. newState.chromecomState = window.history.state.chromecomState;
  344. }
  345. this._updateInternalState(destination, newState.uid);
  346. let newUrl;
  347. if (this._updateUrl && destination?.hash) {
  348. const baseUrl = document.location.href.split("#")[0];
  349. // Prevent errors in Firefox.
  350. if (!baseUrl.startsWith("file://")) {
  351. newUrl = `${baseUrl}#${destination.hash}`;
  352. }
  353. }
  354. if (shouldReplace) {
  355. window.history.replaceState(newState, "", newUrl);
  356. } else {
  357. window.history.pushState(newState, "", newUrl);
  358. }
  359. if (
  360. typeof PDFJSDev !== "undefined" &&
  361. PDFJSDev.test("CHROME") &&
  362. top === window
  363. ) {
  364. // eslint-disable-next-line no-undef
  365. chrome.runtime.sendMessage("showPageAction");
  366. }
  367. }
  368. /**
  369. * @private
  370. */
  371. _tryPushCurrentPosition(temporary = false) {
  372. if (!this._position) {
  373. return;
  374. }
  375. let position = this._position;
  376. if (temporary) {
  377. position = Object.assign(Object.create(null), this._position);
  378. position.temporary = true;
  379. }
  380. if (!this._destination) {
  381. this._pushOrReplaceState(position);
  382. return;
  383. }
  384. if (this._destination.temporary) {
  385. // Always replace a previous *temporary* position.
  386. this._pushOrReplaceState(position, /* forceReplace = */ true);
  387. return;
  388. }
  389. if (this._destination.hash === position.hash) {
  390. return; // The current document position has not changed.
  391. }
  392. if (
  393. !this._destination.page &&
  394. (POSITION_UPDATED_THRESHOLD <= 0 ||
  395. this._numPositionUpdates <= POSITION_UPDATED_THRESHOLD)
  396. ) {
  397. // `this._destination` was set through the user changing the hash of
  398. // the document. Do not add `this._position` to the browser history,
  399. // to avoid "flooding" it with lots of (nearly) identical entries,
  400. // since we cannot ensure that the document position has changed.
  401. return;
  402. }
  403. let forceReplace = false;
  404. if (
  405. this._destination.page >= position.first &&
  406. this._destination.page <= position.page
  407. ) {
  408. // When the `page` of `this._destination` is still visible, do not
  409. // update the browsing history when `this._destination` either:
  410. // - contains an internal destination, since in this case we
  411. // cannot ensure that the document position has actually changed.
  412. // - was set through the user changing the hash of the document.
  413. if (this._destination.dest !== undefined || !this._destination.first) {
  414. return;
  415. }
  416. // To avoid "flooding" the browser history, replace the current entry.
  417. forceReplace = true;
  418. }
  419. this._pushOrReplaceState(position, forceReplace);
  420. }
  421. /**
  422. * @private
  423. */
  424. _isValidPage(val) {
  425. return (
  426. Number.isInteger(val) && val > 0 && val <= this.linkService.pagesCount
  427. );
  428. }
  429. /**
  430. * @private
  431. */
  432. _isValidState(state, checkReload = false) {
  433. if (!state) {
  434. return false;
  435. }
  436. if (state.fingerprint !== this._fingerprint) {
  437. if (checkReload) {
  438. // Potentially accept the history entry, even if the fingerprints don't
  439. // match, when the viewer was reloaded (see issue 6847).
  440. if (
  441. typeof state.fingerprint !== "string" ||
  442. state.fingerprint.length !== this._fingerprint.length
  443. ) {
  444. return false;
  445. }
  446. const [perfEntry] = performance.getEntriesByType("navigation");
  447. if (perfEntry?.type !== "reload") {
  448. return false;
  449. }
  450. } else {
  451. // This should only occur in viewers with support for opening more than
  452. // one PDF document, e.g. the GENERIC viewer.
  453. return false;
  454. }
  455. }
  456. if (!Number.isInteger(state.uid) || state.uid < 0) {
  457. return false;
  458. }
  459. if (state.destination === null || typeof state.destination !== "object") {
  460. return false;
  461. }
  462. return true;
  463. }
  464. /**
  465. * @private
  466. */
  467. _updateInternalState(destination, uid, removeTemporary = false) {
  468. if (this._updateViewareaTimeout) {
  469. // When updating `this._destination`, make sure that we always wait for
  470. // the next 'updateviewarea' event before (potentially) attempting to
  471. // push the current position to the browser history.
  472. clearTimeout(this._updateViewareaTimeout);
  473. this._updateViewareaTimeout = null;
  474. }
  475. if (removeTemporary && destination?.temporary) {
  476. // When the `destination` comes from the browser history,
  477. // we no longer treat it as a *temporary* position.
  478. delete destination.temporary;
  479. }
  480. this._destination = destination;
  481. this._uid = uid;
  482. this._maxUid = Math.max(this._maxUid, uid);
  483. // This should always be reset when `this._destination` is updated.
  484. this._numPositionUpdates = 0;
  485. }
  486. /**
  487. * @private
  488. */
  489. _parseCurrentHash(checkNameddest = false) {
  490. const hash = unescape(getCurrentHash()).substring(1);
  491. const params = parseQueryString(hash);
  492. const nameddest = params.get("nameddest") || "";
  493. let page = params.get("page") | 0;
  494. if (!this._isValidPage(page) || (checkNameddest && nameddest.length > 0)) {
  495. page = null;
  496. }
  497. return { hash, page, rotation: this.linkService.rotation };
  498. }
  499. /**
  500. * @private
  501. */
  502. _updateViewarea({ location }) {
  503. if (this._updateViewareaTimeout) {
  504. clearTimeout(this._updateViewareaTimeout);
  505. this._updateViewareaTimeout = null;
  506. }
  507. this._position = {
  508. hash: location.pdfOpenParams.substring(1),
  509. page: this.linkService.page,
  510. first: location.pageNumber,
  511. rotation: location.rotation,
  512. };
  513. if (this._popStateInProgress) {
  514. return;
  515. }
  516. if (
  517. POSITION_UPDATED_THRESHOLD > 0 &&
  518. this._isPagesLoaded &&
  519. this._destination &&
  520. !this._destination.page
  521. ) {
  522. // If the current destination was set through the user changing the hash
  523. // of the document, we will usually not try to push the current position
  524. // to the browser history; see `this._tryPushCurrentPosition()`.
  525. //
  526. // To prevent `this._tryPushCurrentPosition()` from effectively being
  527. // reduced to a no-op in this case, we will assume that the position
  528. // *did* in fact change if the 'updateviewarea' event was dispatched
  529. // more than `POSITION_UPDATED_THRESHOLD` times.
  530. this._numPositionUpdates++;
  531. }
  532. if (UPDATE_VIEWAREA_TIMEOUT > 0) {
  533. // When closing the browser, a 'pagehide' event will be dispatched which
  534. // *should* allow us to push the current position to the browser history.
  535. // In practice, it seems that the event is arriving too late in order for
  536. // the session history to be successfully updated.
  537. // (For additional details, please refer to the discussion in
  538. // https://bugzilla.mozilla.org/show_bug.cgi?id=1153393.)
  539. //
  540. // To workaround this we attempt to *temporarily* add the current position
  541. // to the browser history only when the viewer is *idle*,
  542. // i.e. when scrolling and/or zooming does not occur.
  543. //
  544. // PLEASE NOTE: It's absolutely imperative that the browser history is
  545. // *not* updated too often, since that would render the viewer more or
  546. // less unusable. Hence the use of a timeout to delay the update until
  547. // the viewer has been idle for `UPDATE_VIEWAREA_TIMEOUT` milliseconds.
  548. this._updateViewareaTimeout = setTimeout(() => {
  549. if (!this._popStateInProgress) {
  550. this._tryPushCurrentPosition(/* temporary = */ true);
  551. }
  552. this._updateViewareaTimeout = null;
  553. }, UPDATE_VIEWAREA_TIMEOUT);
  554. }
  555. }
  556. /**
  557. * @private
  558. */
  559. _popState({ state }) {
  560. const newHash = getCurrentHash(),
  561. hashChanged = this._currentHash !== newHash;
  562. this._currentHash = newHash;
  563. if (
  564. (typeof PDFJSDev !== "undefined" &&
  565. PDFJSDev.test("CHROME") &&
  566. state?.chromecomState &&
  567. !this._isValidState(state)) ||
  568. !state
  569. ) {
  570. // This case corresponds to the user changing the hash of the document.
  571. this._uid++;
  572. const { hash, page, rotation } = this._parseCurrentHash();
  573. this._pushOrReplaceState(
  574. { hash, page, rotation },
  575. /* forceReplace = */ true
  576. );
  577. return;
  578. }
  579. if (!this._isValidState(state)) {
  580. // This should only occur in viewers with support for opening more than
  581. // one PDF document, e.g. the GENERIC viewer.
  582. return;
  583. }
  584. // Prevent the browser history from updating until the new destination,
  585. // as stored in the browser history, has been scrolled into view.
  586. this._popStateInProgress = true;
  587. if (hashChanged) {
  588. // When the hash changed, implying that the 'popstate' event will be
  589. // followed by a 'hashchange' event, then we do *not* want to update the
  590. // browser history when handling the 'hashchange' event (in web/app.js)
  591. // since that would *overwrite* the new destination navigated to below.
  592. //
  593. // To avoid accidentally disabling all future user-initiated hash changes,
  594. // if there's e.g. another 'hashchange' listener that stops the event
  595. // propagation, we make sure to always force-reset `this._blockHashChange`
  596. // after `HASH_CHANGE_TIMEOUT` milliseconds have passed.
  597. this._blockHashChange++;
  598. waitOnEventOrTimeout({
  599. target: window,
  600. name: "hashchange",
  601. delay: HASH_CHANGE_TIMEOUT,
  602. }).then(() => {
  603. this._blockHashChange--;
  604. });
  605. }
  606. // Navigate to the new destination.
  607. const destination = state.destination;
  608. this._updateInternalState(
  609. destination,
  610. state.uid,
  611. /* removeTemporary = */ true
  612. );
  613. if (isValidRotation(destination.rotation)) {
  614. this.linkService.rotation = destination.rotation;
  615. }
  616. if (destination.dest) {
  617. this.linkService.goToDestination(destination.dest);
  618. } else if (destination.hash) {
  619. this.linkService.setHash(destination.hash);
  620. } else if (destination.page) {
  621. // Fallback case; shouldn't be necessary, but better safe than sorry.
  622. this.linkService.page = destination.page;
  623. }
  624. // Since `PDFLinkService.goToDestination` is asynchronous, we thus defer the
  625. // resetting of `this._popStateInProgress` slightly.
  626. Promise.resolve().then(() => {
  627. this._popStateInProgress = false;
  628. });
  629. }
  630. /**
  631. * @private
  632. */
  633. _pageHide() {
  634. // Attempt to push the `this._position` into the browser history when
  635. // navigating away from the document. This is *only* done if the history
  636. // is empty/temporary, since otherwise an existing browser history entry
  637. // will end up being overwritten (given that new entries cannot be pushed
  638. // into the browser history when the 'unload' event has already fired).
  639. if (!this._destination || this._destination.temporary) {
  640. this._tryPushCurrentPosition();
  641. }
  642. }
  643. /**
  644. * @private
  645. */
  646. _bindEvents() {
  647. if (this._boundEvents) {
  648. return; // The event listeners were already added.
  649. }
  650. this._boundEvents = {
  651. updateViewarea: this._updateViewarea.bind(this),
  652. popState: this._popState.bind(this),
  653. pageHide: this._pageHide.bind(this),
  654. };
  655. this.eventBus._on("updateviewarea", this._boundEvents.updateViewarea);
  656. window.addEventListener("popstate", this._boundEvents.popState);
  657. window.addEventListener("pagehide", this._boundEvents.pageHide);
  658. }
  659. /**
  660. * @private
  661. */
  662. _unbindEvents() {
  663. if (!this._boundEvents) {
  664. return; // The event listeners were already removed.
  665. }
  666. this.eventBus._off("updateviewarea", this._boundEvents.updateViewarea);
  667. window.removeEventListener("popstate", this._boundEvents.popState);
  668. window.removeEventListener("pagehide", this._boundEvents.pageHide);
  669. this._boundEvents = null;
  670. }
  671. }
  672. function isDestHashesEqual(destHash, pushHash) {
  673. if (typeof destHash !== "string" || typeof pushHash !== "string") {
  674. return false;
  675. }
  676. if (destHash === pushHash) {
  677. return true;
  678. }
  679. const nameddest = parseQueryString(destHash).get("nameddest");
  680. if (nameddest === pushHash) {
  681. return true;
  682. }
  683. return false;
  684. }
  685. function isDestArraysEqual(firstDest, secondDest) {
  686. function isEntryEqual(first, second) {
  687. if (typeof first !== typeof second) {
  688. return false;
  689. }
  690. if (Array.isArray(first) || Array.isArray(second)) {
  691. return false;
  692. }
  693. if (first !== null && typeof first === "object" && second !== null) {
  694. if (Object.keys(first).length !== Object.keys(second).length) {
  695. return false;
  696. }
  697. for (const key in first) {
  698. if (!isEntryEqual(first[key], second[key])) {
  699. return false;
  700. }
  701. }
  702. return true;
  703. }
  704. return first === second || (Number.isNaN(first) && Number.isNaN(second));
  705. }
  706. if (!(Array.isArray(firstDest) && Array.isArray(secondDest))) {
  707. return false;
  708. }
  709. if (firstDest.length !== secondDest.length) {
  710. return false;
  711. }
  712. for (let i = 0, ii = firstDest.length; i < ii; i++) {
  713. if (!isEntryEqual(firstDest[i], secondDest[i])) {
  714. return false;
  715. }
  716. }
  717. return true;
  718. }
  719. export { isDestArraysEqual, isDestHashesEqual, PDFHistory };