futurepress / epub.js

Enhanced eBooks in the browser.
http://futurepress.org
Other
6.39k stars 1.09k forks source link

Find CFI from href? #986

Open kuuneko opened 4 years ago

kuuneko commented 4 years ago

I'm trying to figure out a way to get a CFI from a href in order to get the CFI for each ToC entry but have been unable to find any method.

Is there a way to get a CFI from a href?

johnfactotum commented 4 years ago

You'll need to load the section first, get the element, then use cfiFromElement to get a CFI. Something like this:

const getCfiFromHref = async (href) => {
    const id= href.split('#')[1]
    const item = book.spine.get(href)
    await item.load(book.load.bind(book))
    const el = id ? item.document.getElementById(id) : item.document.body
    return item.cfiFromElement(el)
}

Note that for book.spine.get(href) to work for ToC entries, you first need to get the full paths by consulting book.packaging.navPath or book.packaging.ncxPath, since the hrefs provided by toc are relative to either the Navigation document (EPUB 3) or NCX file (EPUB 2). (See #469)

chiemekailo commented 1 year ago

hello @johnfactotum, thanks for this great pointer. It worked great. However, once the font size of the displayed section is changed, it misses the mark. Is there a way to factor in the effect of font size change? I was thinking along the lines of ... let options = { "font-size": current_font_size; } await item.load(book.load.bind(book, options)) or ... book.rendition.themes.fontSize = current_font_size; await item.load(book.load.bind(book))