如何在 epub.js 中加载上次访问的页面

How to load the last visited page in epub.js

我正在构建一个简单的 epub reader。我正在使用 epub.js 。我希望应用程序加载最后一页,即用户在关闭 book/reader.

之前所在的页面

这是我的代码:

const epubBook = "{{ bookpath }}";

var book = ePub(epubBook);
var rendition = book.renderTo("viewer", {manager: "continuous", flow: "scrolled", width: "100%", height: "100%", snap: true  } );

var displayed = rendition.display();

book.ready.then(function() {
      const stored = localStorage.getItem(book.key() + '-locations');
      //console.log('metadata:', book.package.metadata);
      bookTitleDiv.innerHTML = book.package.metadata['title']
      if (stored) {
          return book.locations.load(stored);
      } else {
          return book.locations.generate(1024).then( ()=>{
            localStorage.setItem(key, book.locations.save());
          }).catch( err => console.error("error generating locations: ", err)); // Generates CFI for every X characters (Characters per/page)
      }
}).then(function(location) { // This promise will take a little while to return (About 20 seconds or so for Moby Dick)
      localStorage.setItem(book.key() + '-locations', book.locations.save());
});

如果您只保存页码,一旦用户更改书籍的字体大小或调整 reader 的大小,您的代码就会中断。在这种情况下,您的总页码可以 increase/decrease 并且仅仅依靠页码可能会导致您进入错误的页面,或者您最终可能会越界(您的页码 > 书的页数)。

保存页面的安全方法是保存该页面的 CFI 位置字符串(而不是页码)。这些字符串看起来有点像这样:epubcfi(/6/4[chap01ref]!/4[body01]/10[para05]/2/1:3).

如何获取当前页面的CFI位置字符串:


    let location = this.rendition.currentLocation();
    let cfiString = location.start.cfi; // this is what you want to save

导航到特定位置:


    this.rendition.display(cfiString);