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
view.js exports three error classes and a standalone makeBook helper:
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.
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.| Class | When thrown |
|---|---|
ResponseError | The URL fetch returned a non-OK HTTP status. |
NotFoundError | The File or Blob has zero bytes (file not found). |
UnsupportedTypeError | The format could not be detected or is not supported. |
.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.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.close()
Destroys the active renderer, revokes internal state, and clears history. Call this before opening a different book in the same element.init(options)
Navigates to a saved position afteropen(). Call this instead of goTo() when restoring a session.
A previously saved
view.lastLocation value. When provided the view navigates to that position and pushes it onto the history stack.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).goTo(target)
Navigates to a target location and pushes it onto the history stack.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.goToFraction(frac)
Navigates to a position expressed as a fraction (0–1) of the full book. UnlikegoTo({ fraction }), this uses sectionProgress directly and pushes a fraction object onto the history stack.
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 bydistance pixels.
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.
select(target)
Navigates to a target and selects the text at that location. The target is resolved the same way as ingoTo().
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.
The CFI string identifying the annotated range.
deleteAnnotation(annotation)
Removes a previously added annotation.The CFI string of the annotation to remove.
showAnnotation(annotation)
Navigates to the annotation’s location and emits ashow-annotation event.
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.
The search query string.
If provided, restricts the search to the single section at this index. Otherwise the whole book is searched.
Custom draw function for search highlights. Defaults to
Overlayer.outline.Options passed to the
draw function.clearSearch()
Removes all search highlight annotations and clears internal search state.initTTS(granularity?, highlight?)
Initialises the TTS controller for the currently visible section.Segmentation granularity passed to the
TTS constructor. Defaults to 'word'. Accepts any value supported by Intl.Segmenter (e.g. 'sentence').Custom highlight callback. Receives a
Range and scrolls to it. Defaults to renderer.scrollToAnchor(range, true).startMediaOverlay()
Starts EPUB Media Overlay playback from the currently visible section index. Only available afteropen() 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.Section index.
A DOM
Range within that section’s document.{ tocItem, pageItem } where each item has .label and .href.
getTOCItemOf(target)
Resolves a navigation target to the matching TOC item.Same types as
goTo().getCFI(index, range)
Constructs a full CFI string from a section index and a DOM range.Section index.
A DOM
Range. If omitted, returns the base (section-level) CFI.resolveCFI(cfi)
Resolves a CFI string to a{ index, anchor } object.
A full EPUB CFI string.
{ index: number, anchor: (doc: Document) => Range | Element }.
resolveNavigation(target)
Resolves any navigation target (CFI, href, section index, or fraction object) to{ index, anchor }.
Same types as
goTo().Properties
| Property | Type | Description |
|---|---|---|
view.book | object | The current book object, set after open(). |
view.renderer | HTMLElement | The active renderer element (foliate-paginator or foliate-fxl). |
view.language | object | Language info derived from book.metadata.language: { canonical, locale, isCJK, direction }. |
view.isFixedLayout | boolean | true when book.rendition.layout === 'pre-paginated'. |
view.lastLocation | object | The detail payload from the most recent relocate event. |
view.history | History | Navigation history object (see below). |
view.tts | TTS | null | TTS instance after initTTS(), otherwise null. |
view.mediaOverlay | object | null | Media overlay controller for EPUB books that have one, otherwise null. |
view.history
A customHistory object that is an EventTarget. It does not use the browser’s window.history.
| Member | Description |
|---|---|
.canGoBack | boolean — true when there is a previous entry. |
.canGoForward | boolean — true when there is a forward entry. |
.back() | Navigate to the previous history entry. |
.forward() | Navigate to the next history entry. |
Events
All events areCustomEvents dispatched on the <foliate-view> element.
relocate
Fired whenever the visible location changes (page turn, scroll, initial load, or history navigation).A full CFI string representing the current position.
Overall book reading progress from 0 to 1, weighted by section byte sizes.
Index of the currently visible section.
The deepest matching TOC item at the current position, or
null.The deepest matching page list item at the current position, or
null.A DOM
Range covering the visible area of the current page.Section-level progress information from
SectionProgress.Estimated total page count (available when section progress data is present).
The start fraction of the current section within the full book.
load
Fired after a section document is loaded into the renderer iframe.The loaded section’s
Document object.The section index.
link
Fired when the reader clicks an internal link. The default action (if not cancelled) is to callview.goTo(href).
The anchor element that was clicked.
The resolved absolute href.
e.preventDefault() to suppress navigation:
external-link
Fired when the reader clicks a link thatbook.isExternal() identifies as external. The default action is to call globalThis.open(href_, '_blank').
The anchor element that was clicked.
The raw
href attribute value (not resolved).draw-annotation
Fired when an annotated section becomes visible and the highlight needs to be drawn. Your handler must calldraw(func, opts) to render the highlight.
Call with
(drawFunction, drawOptions) to render the annotation. The drawFunction receives (svg, range, viewport, doc) and returns an SVG element.The original annotation object passed to
addAnnotation().The section document in which the annotation lives.
The DOM
Range corresponding to the CFI.show-annotation
Fired when the user clicks an existing annotation highlight, or whenshowAnnotation() is called.
The CFI string of the annotation.
The section index of the annotation.
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.The section index for which the overlayer was created.