Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/johnfactotum/foliate-js/llms.txt

Use this file to discover all available pages before exploring further.

view.js is the main entry point of foliate-js. It registers the <foliate-view> custom element, which acts as a high-level orchestrator: it auto-detects book format, instantiates the correct renderer (foliate-paginator or foliate-fxl), tracks reading position, manages navigation history, runs search, and coordinates annotations and TTS. Import the module once and then work entirely through the DOM element.

Import

import './foliate-js/view.js'

const view = document.createElement('foliate-view')
document.body.append(view)
In addition to the custom element, view.js exports three error classes and a standalone makeBook helper:
import { makeBook, ResponseError, NotFoundError, UnsupportedTypeError } from './foliate-js/view.js'

makeBook(file)

Resolves a file to a book object that implements the foliate-js book interface. view.open() calls this internally, but you can call it directly when you need the book object before opening a view.
file
string | File | Blob | DirectoryEntry
required
The source to load. A URL string is fetched first; a File or Blob is inspected by magic bytes; a FileSystemDirectoryEntry is read as an unpacked EPUB directory.
Throws one of the following on failure:
ClassWhen thrown
ResponseErrorThe URL fetch returned a non-OK HTTP status.
NotFoundErrorThe File or Blob has zero bytes (file not found).
UnsupportedTypeErrorThe format could not be detected or is not supported.
Format detection order: CBZ by MIME type or .cbz extension → FBZ → EPUB (any other ZIP) → PDF by magic bytes → MOBI/KF8 → FB2 by MIME type or .fb2 extension.

Methods

open(book)

Opens a book in the view. Automatically creates the appropriate renderer.
book
string | File | Blob | DirectoryEntry | object
required
Accepts the same types as makeBook(). Any value that is not already a book object is passed through makeBook() for format detection. Passing an already-constructed book object skips format detection entirely.
// Open by URL
await view.open('https://example.com/book.epub')

// Open by File object (e.g., from <input type="file">)
await view.open(fileInputEl.files[0])

// Open a pre-constructed book object
const book = await makeBook(file)
await view.open(book)

close()

Destroys the active renderer, revokes internal state, and clears history. Call this before opening a different book in the same element.
view.close()

init(options)

Navigates to a saved position after open(). Call this instead of goTo() when restoring a session.
options.lastLocation
object
A previously saved view.lastLocation value. When provided the view navigates to that position and pushes it onto the history stack.
options.showTextStart
boolean
When true and no lastLocation is given, navigates to the first landmark of type bodymatter or text (the start of the main text, skipping front matter).
// Restore a saved session
const saved = JSON.parse(localStorage.getItem('lastLocation'))
await view.init({ lastLocation: saved })

// Or start from the beginning of the text body
await view.init({ showTextStart: true })

goTo(target)

Navigates to a target location and pushes it onto the history stack.
target
string | number | object
required
Accepts a CFI string, an href string, a section index number, or a fraction object { fraction } where fraction is a number from 0 to 1 representing position across the full book.
await view.goTo('epubcfi(/6/4!/4/2/1:0)')  // CFI
await view.goTo('chapter-02.xhtml#section-3')  // href
await view.goTo(5)                             // section index
await view.goTo({ fraction: 0.5 })            // mid-book

goToFraction(frac)

Navigates to a position expressed as a fraction (0–1) of the full book. Unlike goTo({ fraction }), this uses sectionProgress directly and pushes a fraction object onto the history stack.
frac
number
required
A number from 0 (start) to 1 (end) representing the reading position across all sections.

prev([distance]) / next([distance])

Navigate backward or forward. In paginated mode, advances one page; in scrolled mode, scrolls by distance pixels.
distance
number
Optional scroll distance in pixels. Only used in scrolled flow mode. Defaults to the container’s full scroll size.

goLeft() / goRight()

Direction-aware navigation. goLeft() calls prev() for LTR books and next() for RTL books; goRight() is the inverse. Use these for keyboard or button controls so your UI works correctly with right-to-left books.
document.addEventListener('keydown', e => {
    if (e.key === 'ArrowLeft') view.goLeft()
    if (e.key === 'ArrowRight') view.goRight()
})

select(target)

Navigates to a target and selects the text at that location. The target is resolved the same way as in goTo().
target
string | number | object
required
Same types as goTo().

deselect()

Clears all text selections in the current renderer document.

addAnnotation(annotation)

Draws an annotation highlight for the given CFI. When the section containing the CFI is loaded, view.js emits a draw-annotation event so you can supply the draw function.
annotation.value
string
required
The CFI string identifying the annotated range.

deleteAnnotation(annotation)

Removes a previously added annotation.
annotation.value
string
required
The CFI string of the annotation to remove.

showAnnotation(annotation)

Navigates to the annotation’s location and emits a show-annotation event.
annotation.value
string
required
The CFI string of the annotation to show.

search(opts)

An async generator that searches the book and yields results incrementally. Highlights are drawn automatically as results are found. Yields 'done' when the search is complete.
opts.query
string
required
The search query string.
opts.index
number
If provided, restricts the search to the single section at this index. Otherwise the whole book is searched.
opts.draw
function
Custom draw function for search highlights. Defaults to Overlayer.outline.
opts.drawOptions
object
Options passed to the draw function.
for await (const result of view.search({ query: 'Moby Dick' })) {
    if (result === 'done') break
    if (result.subitems) {
        // whole-book results: { label, subitems: [{ cfi, excerpt }] }
        for (const { cfi, excerpt } of result.subitems) console.log(cfi, excerpt)
    } else if (result.progress != null) {
        // progress update: { progress } (0–1)
    } else {
        // single-section results: { cfi, excerpt }
    }
}

clearSearch()

Removes all search highlight annotations and clears internal search state.

initTTS(granularity?, highlight?)

Initialises the TTS controller for the currently visible section.
granularity
string
Segmentation granularity passed to the TTS constructor. Defaults to 'word'. Accepts any value supported by Intl.Segmenter (e.g. 'sentence').
highlight
function
Custom highlight callback. Receives a Range and scrolls to it. Defaults to renderer.scrollToAnchor(range, true).
await view.initTTS('sentence')
// view.tts is now available

startMediaOverlay()

Starts EPUB Media Overlay playback from the currently visible section index. Only available after open() on a book that has media overlay data.

getSectionFractions()

Returns an array of numbers, one per section, where each number is the fraction (0–1) at which that section begins within the full book. Useful for rendering a progress bar with section markers.

getProgressOf(index, range)

Returns the TOC and page list items that correspond to a given section and DOM range.
index
number
required
Section index.
range
Range
required
A DOM Range within that section’s document.
Returns { tocItem, pageItem } where each item has .label and .href.

getTOCItemOf(target)

Resolves a navigation target to the matching TOC item.
target
string | number | object
required
Same types as goTo().

getCFI(index, range)

Constructs a full CFI string from a section index and a DOM range.
index
number
required
Section index.
range
Range
A DOM Range. If omitted, returns the base (section-level) CFI.

resolveCFI(cfi)

Resolves a CFI string to a { index, anchor } object.
cfi
string
required
A full EPUB CFI string.
Returns { index: number, anchor: (doc: Document) => Range | Element }.

resolveNavigation(target)

Resolves any navigation target (CFI, href, section index, or fraction object) to { index, anchor }.
target
string | number | object
required
Same types as goTo().

Properties

PropertyTypeDescription
view.bookobjectThe current book object, set after open().
view.rendererHTMLElementThe active renderer element (foliate-paginator or foliate-fxl).
view.languageobjectLanguage info derived from book.metadata.language: { canonical, locale, isCJK, direction }.
view.isFixedLayoutbooleantrue when book.rendition.layout === 'pre-paginated'.
view.lastLocationobjectThe detail payload from the most recent relocate event.
view.historyHistoryNavigation history object (see below).
view.ttsTTS | nullTTS instance after initTTS(), otherwise null.
view.mediaOverlayobject | nullMedia overlay controller for EPUB books that have one, otherwise null.

view.history

A custom History object that is an EventTarget. It does not use the browser’s window.history.
MemberDescription
.canGoBackbooleantrue when there is a previous entry.
.canGoForwardbooleantrue when there is a forward entry.
.back()Navigate to the previous history entry.
.forward()Navigate to the next history entry.

Events

All events are CustomEvents dispatched on the <foliate-view> element.

relocate

Fired whenever the visible location changes (page turn, scroll, initial load, or history navigation).
cfi
string
A full CFI string representing the current position.
fraction
number
Overall book reading progress from 0 to 1, weighted by section byte sizes.
index
number
Index of the currently visible section.
tocItem
object | null
The deepest matching TOC item at the current position, or null.
pageItem
object | null
The deepest matching page list item at the current position, or null.
range
Range
A DOM Range covering the visible area of the current page.
location
object
Section-level progress information from SectionProgress.
pageCount
number
Estimated total page count (available when section progress data is present).
sectionFraction
number
The start fraction of the current section within the full book.
view.addEventListener('relocate', e => {
    const { cfi, fraction, tocItem } = e.detail
    localStorage.setItem('lastLocation', JSON.stringify(cfi))
    document.title = tocItem?.label ?? ''
})

load

Fired after a section document is loaded into the renderer iframe.
doc
Document
The loaded section’s Document object.
index
number
The section index.

Fired when the reader clicks an internal link. The default action (if not cancelled) is to call view.goTo(href).
a
HTMLAnchorElement
The anchor element that was clicked.
href
string
The resolved absolute href.
This event is cancelable. Call e.preventDefault() to suppress navigation:
view.addEventListener('link', e => {
    e.preventDefault()            // stop automatic navigation
    myCustomNavigation(e.detail.href)
})

Fired when the reader clicks a link that book.isExternal() identifies as external. The default action is to call globalThis.open(href_, '_blank').
a
HTMLAnchorElement
The anchor element that was clicked.
href_
string
The raw href attribute value (not resolved).
This event is cancelable.

draw-annotation

Fired when an annotated section becomes visible and the highlight needs to be drawn. Your handler must call draw(func, opts) to render the highlight.
draw
function
Call with (drawFunction, drawOptions) to render the annotation. The drawFunction receives (svg, range, viewport, doc) and returns an SVG element.
annotation
object
The original annotation object passed to addAnnotation().
doc
Document
The section document in which the annotation lives.
range
Range
The DOM Range corresponding to the CFI.
import { Overlayer } from './foliate-js/overlayer.js'

view.addEventListener('draw-annotation', e => {
    const { draw, annotation } = e.detail
    draw(Overlayer.highlight, { color: annotation.color ?? 'yellow' })
})

show-annotation

Fired when the user clicks an existing annotation highlight, or when showAnnotation() is called.
value
string
The CFI string of the annotation.
index
number
The section index of the annotation.
range
Range
The DOM Range of the annotation in the current document.

create-overlay

Fired when the overlayer for a section is first created. Use this to re-apply annotations after a section reload.
index
number
The section index for which the overlayer was created.

Build docs developers (and LLMs) love