Restore last seen page when reopening a document

Q: How can I jump to the last seen page of a document?

A: You can follow these steps in order to do so:

  1. Add a listener for viewState.currentPageIndex.change events.

  2. On the event listener, store the current visited page. If you only need to keep it client-side, you can use local storage for that. Otherwise, you can send that information to your backend.

  3. Once the user returns to the same document, retrieve the last seen pageIndex and move the instance to it.

Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const STORAGE_KEY = "lastViewedPageMap";

// In production, this might come as input.
const documentId = "7KQ5466P9XZ4KCG1MFHQBAMC21";

PSPDFKit.load(
  {
    documentId, 
    container: "#main",
    // ...
  }).then(instance => {
    // localStorage is used just as an example.
    const lastViewedPageString = localStorage.getItem(STORAGE_KEY);
    if (lastViewedPageString) {
      const map = JSON.parse(lastViewedPageString);
      const page = map[documentId];
      if (page) {
        instance.setViewState(v => v.set("currentPageIndex", parseInt(page)));
      }
    }

    instance.addEventListener("viewState.currentPageIndex.change", page => {
      const current = localStorage.getItem(STORAGE_KEY);

      const map = current ? JSON.parse(current) : {};

      localStorage.setItem(
        STORAGE_KEY,
        JSON.stringify({ ...map, [documentId]: page })
      );
    });
  })

This has been tested with PSPDFKit for Web 2020.3.0.