Creates a new Book
Parameters
url(string | ArrayBuffer) URL, Path or ArrayBufferoptionsobject to pass to the book
Examples
ePub("/path/to/book.epub", {})Returns Book a new Book object
An Epub representation with methods for the loading, parsing and manipulation of its contents.
Parameters
urlstring?optionsobject?options.requestMethodmethod? a request function to use instead of the defaultoptions.requestCredentialsboolean send the xhr request withCredentials (optional, defaultundefined)options.requestHeadersobject send the xhr request headers (optional, defaultundefined)options.encodingstring optional to pass 'binary' or base64' for archived Epubs (optional, defaultbinary)options.replacementsstring use base64, blobUrl, or none for replacing assets in archived Epubs (optional, defaultnone)options.canonicalmethod? optional function to determine canonical urls for a pathoptions.openAsstring? optional string to determine the input type
Examples
new Book("/path/to/book.epub", {})new Book({ replacements: "blobUrl" })Returns Book
Open a epub or url
Parameters
input(string | ArrayBuffer) Url, Path or ArrayBufferwhatstring force opening as a certain type (optional, default"binary","base64","epub","opf","json","directory")
Examples
book.open("/path/to/book.epub")Returns Promise of when the book has been loaded
Load a resource from the Book
Parameters
pathstring path to the resource to load
Returns Promise returns a promise with the requested resource
Resolve a path to it's absolute position in the Book
Parameters
Returns string the resolved path string
Get a canonical link to a path
Parameters
pathstring
Returns string the canonical path string
Gets a Section of the Book from the Spine
Alias for book.spine.get
Parameters
targetstring
Returns Section
Sugar to render a book to an element
Parameters
Returns Rendition
Set if request should use withCredentials
Parameters
credentialsboolean
Set headers request should use
Parameters
headersobject
Get the cover url if there is a cover
Returns Promise<?string> Promise resolves with maybe a url string
Find a DOM Range for a given CFI Range
Parameters
cfiRangeEpubCFI a epub cfi range
Returns Range
Generates the Book Key using the identifier in the manifest or other string provided
Parameters
identifierstring? to use instead of metadata identifier
Returns string key
Destroy the Book and all associated objects
Type: Spine
Type: Locations
Type: Navigation
Type: PageList
creates a Url object for parsing and manipulation of a url string
Parameters
urlStringstring a url string (relative or absolute)baseStringstring? optional base for the url, default to window.location.href
Returns Path
Resolves a relative path to a absolute url
Parameters
whatstring
Returns string url
Resolve a path relative to the url
Parameters
whatstring
Returns string path
Returns string
Creates a Path object for parsing and manipulation of a path strings
Uses a polyfill for Nodejs path: https://nodejs.org/api/path.html
Parameters
pathStringstring a url string (relative or absolute)
Parse the path: https://nodejs.org/api/path.html#path_path_parse_path
Parameters
whatstring
Returns object
Parameters
whatstring
Returns boolean
Check if path ends with a directory
Parameters
whatstring
Returns boolean
Resolve a path against the directory of the Path
https://nodejs.org/api/path.html#path_path_resolve_paths
Parameters
whatstring
Returns string resolved
Resolve a path relative to the directory of the Path
https://nodejs.org/api/path.html#path_path_relative_from_to
Parameters
whatstring
Returns string relative
Return the path string
Returns string path
A collection of Spine Items
Unpack items from a opf into spine items
Parameters
_packagePackagingresolvermethod URL resolvercanonicalmethod Resolve canonical url
Get an item from the spine
Parameters
Examples
spine.get();spine.get(1);spine.get("chap1.html");spine.get("#id1234");Returns Section section
Loop over the Sections in the Spine
Returns method forEach
Find the first Section in the Spine
Returns Section first section
Find the last Section in the Spine
Returns Section last section
Represents a Section of the Book
In most books this is equivalent to a Chapter
Parameters
Load the section from its url
Parameters
_requestmethod? a request method to use for loading
Returns document a promise with the xml document
Render the contents of a section
Parameters
_requestmethod? a request method to use for loading
Returns string output a serialized XML Document
Find a string in a section
Parameters
_querystring The query string to find
Returns Array<object> A list of matches, with form {cfi, excerpt}
Reconciles the current chapters layout properties with the global layout properties.
Parameters
globalLayoutobject The global layout settings object, chapter properties string
Returns object layoutProperties Object with layout properties
Get a CFI from a Range in the Section
Parameters
_rangerange
Returns string cfi an EpubCFI string
Get a CFI from an Element in the Section
Parameters
elelement
Returns string cfi an EpubCFI string
Unload the section document
Find Locations for a Book
Parameters
Load all of sections in the book to generate locations
Parameters
charsint how many chars to split on
Returns object locations
Get a location from an EpubCFI
Parameters
cfiEpubCFI
Returns number
Get a percentage position in locations from an EpubCFI
Parameters
cfiEpubCFI
Returns number
Get a percentage position from a location index
Parameters
loclocationnumber
Returns number
Get an EpubCFI from location index
Parameters
locnumber
Returns EpubCFI cfi
Get an EpubCFI from location percentage
Parameters
percentagenumber
Returns EpubCFI cfi
Load locations from JSON
Parameters
locationsjson
Save locations to JSON
Returns json
Get the current location
Set the current location
Parameters
curr
Locations length
Handles Parsing and Accessing an Epub Container
Parameters
containerDocumentdocument? xml document
Parse the Container XML
Parameters
containerDocumentdocument
Open Packaging Format Parser
Parameters
packageDocumentdocument OPF XML
Parse OPF XML
Parameters
packageDocumentdocument OPF XML
Returns object parsed package parts
Load JSON Manifest
Parameters
jsonpackageDocumentdocument OPF XML
Returns object parsed package parts
Navigation Parser
Parameters
xmldocument navigation html / xhtml / ncx
Parse out the navigation items
Parameters
xmldocument navigation html / xhtml / ncx
Get an item from the navigation
Parameters
targetstring
Returns object navItem
Get a landmark by type List of types: https://idpf.github.io/epub-vocabs/structure/
Parameters
typestring
Returns object landmarkItem
Load Spine Items
Parameters
jsonobject the items to be loaded
Returns Array navItems
forEach pass through
Parameters
fnFunction function to run on each item
Returns method forEach loop
Handle Package Resources
Parameters
manifestManifestoptionsobject?
Create a url to a resource
Parameters
urlstring
Returns Promise<string> Promise resolves with url string
Create blob urls for all the assets
Returns Promise returns replacement urls
Resolve all resources URLs relative to an absolute URL
Parameters
absolutestring to be resolved toresolverresolver?
Returns Array<string> array with relative Urls
Get a URL for a resource
Parameters
pathstring
Returns string url
Substitute urls in content, with replacements, relative to a url if provided
Parameters
Returns string content with urls substituted
Page List Parser
Parameters
xmldocument?
Parse PageList Xml
Parameters
xmldocument
Get a PageList result from a EpubCFI
Parameters
cfistring EpubCFI String
Returns number page
Get an EpubCFI from a Page List Item
Parameters
Returns string cfi
Get a Page from Book percentage
Parameters
percentnumber
Returns number page
Returns a value between 0 - 1 corresponding to the location of a page
Parameters
pgnumber the page
Returns number percentage
Returns a value between 0 - 1 corresponding to the location of a cfi
Parameters
cfistring EpubCFI String
Returns number percentage
Destroy
Handles Unzipping a requesting files from an Epub Archive
Open an archive
Parameters
inputbinaryisBase64boolean? tells JSZip if the input data is base64 encoded
Returns Promise zipfile
Load and Open an archive
Parameters
Returns Promise zipfile
Request a url from the archive
Parameters
Returns Promise<(Blob | string | JSON | Document | XMLDocument)>
Get a Blob from Archive by Url
Parameters
Returns Blob
Get Text from Archive by Url
Parameters
Returns string
Get a base64 encoded result from Archive by Url
Parameters
Returns string base64 encoded
Create a Url from an unarchived item
Parameters
urlstringoptions
Returns Promise url promise with Url string
Revoke Temp Url for a archive item
Parameters
urlstring url of the item in the archive
Displays an Epub as a series of Views for each Section. Requires Manager and View class to handle specifics of rendering the section content.
Parameters
bookBookoptionsobject?options.widthnumber?options.heightnumber?options.ignoreClassstring? class for the cfi parser to ignoreoptions.manager(string | function | object) (optional, default'default')options.view(string | function) (optional, default'iframe')options.layoutstring? layout to forceoptions.spreadstring? force spread valueoptions.minSpreadWidthnumber? overridden by spread: none (never) / both (always)options.stylesheetstring? url of stylesheet to be injectedoptions.resizeOnOrientationChangeboolean? false to disable orientation eventsoptions.scriptstring? url of script to be injected
Set the manager function
Parameters
managerfunction
Require the manager from passed string, or as a class function
Parameters
Returns method
Require the view from passed string, or as a class function
Parameters
Returns view
Start the rendering
Returns Promise rendering has started
Call to attach the container to an element in the dom Container must be attached before rendering can begin
Parameters
elementelement to attach to
Returns Promise
Display a point in the book The request will be added to the rendering Queue, so it will wait until book is opened, rendering started and all other rendering tasks have finished to be called.
Parameters
targetstring Url or EpubCFI
Returns Promise
Move the Rendition to a specific offset Usually you would be better off calling display()
Parameters
offsetobject
Trigger a resize of the views
Parameters
Clear all rendered views
Go to the next "page" in the rendition
Returns Promise
Go to the previous "page" in the rendition
Returns Promise
Adjust the flow of the rendition to paginated or scrolled (scrolled-continuous vs scrolled-doc are handled by different view managers)
Parameters
flowstring
Adjust the layout of the rendition to reflowable or pre-paginated
Parameters
settingsobject
Adjust if the rendition uses spreads
Parameters
spreadstring none | auto (TODO: implement landscape, portrait, both)minint min width to use spreads at
Adjust the direction of the rendition
Parameters
dirstring
Report the current location
Get the Current Location object
Returns (displayedLocation | promise) location (may be a promise)
Remove and Clean Up the Rendition
Get a Range from a Visible CFI
Parameters
Returns range
Get the Contents object of each rendered view
Get the views member from the manager
Returns Views
Adds Hook methods to the Rendition prototype
Type: object
Type: Themes
Type: Annotations
A Rendered Location Range
Properties
Hooks allow for injecting functions that must all complete in order before finishing They will execute in parallel but all must finish before continuing Functions may return a promise if they are async.
Parameters
contextany scope of this
Examples
this.content = new EPUBJS.Hook(this);Adds a function to be run before a hook completes
Examples
this.content.register(function(){...});Triggers a hook to run all functions
Examples
this.content.trigger(args).then(function(){...});Queue for handling tasks one at a time
Parameters
contextscope what this will resolve to in the tasks
Add an item to the queue
Returns Promise
Run one item
Returns Promise
Run all tasks sequentially, at convince
Returns Promise
Flush all, as quickly as possible
Returns Promise
Clear all items in wait
Get the number of tasks in the queue
Returns number tasks
Pause a running queue
End the queue
Figures out the CSS values to apply for a layout
Parameters
settingsobject
Switch the flow between paginated and scrolled
Parameters
flowstring paginated | scrolled
Returns string simplified flow
Switch between using spreads or not, and set the width at which they switch to single.
Parameters
Returns boolean spread true | false
Calculate the dimensions of the pagination
Parameters
_widthnumber width of the rendering_heightnumber height of the rendering_gapnumber width of the gap between columns
Apply Css to a Document
Parameters
contentsContents
Returns Promise
Count number of pages
Parameters
Returns {spreads: Number, pages: Number}
Themes to apply to displayed content
Parameters
renditionRendition
Add themes to be used by a rendition
Examples
themes.register("light", "http://example.com/light.css")themes.register("light", { "body": { "color": "purple"}})themes.register({ "light" : {...}, "dark" : {...}})Add a default theme to be used by a rendition
Parameters
Examples
themes.register("http://example.com/default.css")themes.register({ "body": { "color": "purple"}})Register themes object
Parameters
themesobject
Register a url
Parameters
Register rule
Parameters
Select a theme
Parameters
namestring
Update a theme
Parameters
namestring
Inject all themes into contents
Parameters
contentsContents
Add Theme to contents
Parameters
Add override
Parameters
Add all overrides
Parameters
contentscontentContent
Adjust the font size of a rendition
Parameters
sizenumber
Adjust the font-family of a rendition
Parameters
fstring
Handles managing adding & removing Annotations
Parameters
renditionRendition
Add an annotation to store
Parameters
typestring Type of annotation to add: "highlight", "underline", "mark"cfiRangeEpubCFI EpubCFI range to attach annotation todataobject Data to assign to annotationcbfunction? Callback after annotation is addedclassNamestring CSS class to assign to annotationstylesobject CSS styles to assign to annotation
Returns Annotation annotation
Remove an annotation from store
Parameters
cfiRangeEpubCFI EpubCFI range the annotation is attached totypestring Type of annotation to add: "highlight", "underline", "mark"
Add a highlight to the store
Parameters
cfiRangeEpubCFI EpubCFI range to attach annotation todataobject Data to assign to annotationcbfunction Callback after annotation is addedclassNamestring CSS class to assign to annotationstylesobject CSS styles to assign to annotation
Add a underline to the store
Parameters
cfiRangeEpubCFI EpubCFI range to attach annotation todataobject Data to assign to annotationcbfunction Callback after annotation is addedclassNamestring CSS class to assign to annotationstylesobject CSS styles to assign to annotation
Add a mark to the store
Parameters
cfiRangeEpubCFI EpubCFI range to attach annotation todataobject Data to assign to annotationcbfunction Callback after annotation is added
iterate over annotations in the store
[Not Implemented] Show annotations
[Not Implemented] Hide annotations
Annotation object
Parameters
$0Object$0.type$0.cfiRange$0.data$0.sectionIndex$0.cb$0.className$0.styles
optionsobjectoptions.typestring Type of annotation to add: "highlight", "underline", "mark"options.cfiRangeEpubCFI EpubCFI range to attach annotation tooptions.dataobject Data to assign to annotationoptions.sectionIndexint Index in the Spine of the Section annotation belongs tooptions.cbfunction? Callback after annotation is added
classNamestring CSS class to assign to annotationstylesobject CSS styles to assign to annotation
Returns Annotation annotation
Update stored data
Parameters
dataobject
Add to a view
Parameters
viewView
Remove from a view
Parameters
viewView
[Not Implemented] Get text of an annotation
Parsing and creation of EpubCFIs: http://www.idpf.org/epub/linking/cfi/epub-cfi.html
Implements:
- Character Offset: epubcfi(/6/4[chap01ref]!/4[body01]/10[para05]/2/1:3)
- Simple Ranges : epubcfi(/6/4[chap01ref]!/4[body01]/10[para05],/2/1:1,/3:4)
Does Not Implement:
- Temporal Offset (~)
- Spatial Offset (@)
- Temporal-Spatial Offset (~ + @)
- Text Location Assertion ([)
Parameters
cfiFrom(string | Range | Node)?base(string | object)?ignoreClassstring? class to ignore when parsing DOM
Parse a cfi string to a CFI object representation
Parameters
cfiStrstring
Returns object cfi
Convert CFI to a epubcfi(...) string
Returns string epubcfi
Compare which of two CFIs is earlier in the text
Parameters
cfiOnecfiTwo
Returns number First is earlier = -1, Second is earlier = 1, They are equal = 0
Create a CFI object from a Range
Parameters
Returns object cfi
Create a CFI object from a Node
Parameters
Returns object cfi
Creates a DOM range representing a CFI
Parameters
Returns Range
Check if a string is wrapped with "epubcfi()"
Parameters
strstring
Returns boolean
Collapse a CFI Range to a single CFI Position
Parameters
toStartboolean (optional, defaultfalse)
Handles DOM manipulation, queries and events for View contents
Parameters
docdocument Documentcontentelement Parent Element (typically Body)cfiBasestring Section component of CFIssectionIndexnumber Index in Spine of Conntent's Section
Get or Set width
Parameters
wnumber?
Returns number width
Get or Set height
Parameters
hnumber?
Returns number height
Get or Set width of the contents
Parameters
wnumber?
Returns number width
Get or Set height of the contents
Parameters
hnumber?
Returns number height
Get the width of the text using Range
Returns number width
Get the height of the text using Range
Returns number height
Get documentElement scrollWidth
Returns number width
Get documentElement scrollHeight
Returns number height
Set overflow css style of the contents
Parameters
overflowstring?
Set overflowX css style of the documentElement
Parameters
overflowstring?
Set overflowY css style of the documentElement
Parameters
overflowstring?
Set Css styles on the contents element (typically Body)
Parameters
Get or Set the viewport element
Parameters
optionsobject?
Get the documentElement
Returns element documentElement
Get the location offset of a EpubCFI or an #id
Parameters
Append a stylesheet link to the document head
Parameters
srcstring url
Append stylesheet rules to a generate stylesheet Array: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule Object: https://github.com/desirable-objects/json-to-css
Parameters
Append a script tag to the document head
Parameters
srcstring url
Returns Promise loaded
Add a class to the contents container
Parameters
classNamestring
Remove a class from the contents container
Parameters
classNameremoveClassstring
Get a Dom Range from EpubCFI
Parameters
Returns Range range
Get an EpubCFI from a Dom Range
Parameters
Returns EpubCFI cfi
Get an EpubCFI from a Dom node
Parameters
Returns EpubCFI cfi
Size the contents to a given width and height
Parameters
Apply columns to the contents for pagination
Parameters
Scale contents from center
Parameters
Fit contents into a fixed width and height
Parameters
Set the direction of the text
Parameters
dirstring "rtl" | "ltr" (optional, default"ltr")
Set the writingMode of the text
Parameters
modestring "horizontal-tb" | "vertical-rl" | "vertical-lr" (optional, default"horizontal-tb")
Get DOM events that are listened for and passed along
Map text locations to CFI ranges
Parameters
layoutLayout Layout to applydirectionstring Text direction (optional, default"ltr")axisstring vertical or horizontal axis (optional, default"horizontal")devboolean? toggle developer highlighting
Find CFI pairs for entire section at once
Parameters
view
Find CFI pairs for a page
Parameters
contentsContents Contents from viewcfiBasestring string of the base for a cfistartnumber position to start atendnumber position to end at
Set the axis for mapping
Parameters
axisstring horizontal | vertical
Returns boolean is it horizontal?
Core Utilities and Helpers
Vendor prefixed requestAnimationFrame
Returns function requestAnimationFrame
Generates a UUID based on: http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
Returns string uuid
Gets the height of a document
Returns number height
Checks if a node is an element
Parameters
objobject
Returns boolean
Parameters
nany
Returns boolean
Parameters
nany
Returns boolean
Get a prefixed css property
Parameters
unprefixedstring
Returns string
Apply defaults to an object
Parameters
objobject
Returns object
Extend properties of an object
Parameters
targetobject
Returns object
Fast quicksort insert for sorted array -- based on: http://stackoverflow.com/questions/1344500/efficient-way-to-insert-a-number-into-a-sorted-array-of-numbers
Parameters
Returns number location (in array)
Finds where something would fit into a sorted array
Parameters
Returns number location (in array)
Finds index of something in a sorted array Returns -1 if not found
Parameters
Returns number index (in array) or -1
Find the bounds of an element taking padding and margin into account
Parameters
elelement
Returns {width: Number, height: Number}
Find the bounds of an element taking padding, margin and borders into account
Parameters
elelement
Returns {width: Number, height: Number}
Find the bounds of any node allows for getting bounds of text nodes by wrapping them in a range
Parameters
nodenode
Returns BoundingClientRect
Find the equivalent of getBoundingClientRect of a browser window
Returns {width: Number, height: Number, top: Number, left: Number, right: Number, bottom: Number}
Gets the index of a node in its parent
Parameters
Returns number index
Gets the index of a text node in its parent
Parameters
textNodenode
Returns number index
Gets the index of an element node in its parent
Parameters
elementNodeelement
Returns number index
Check if extension is xml
Parameters
extstring
Returns boolean
Create a new blob
Parameters
contentanymimestring
Returns Blob
Create a new blob url
Parameters
contentanymimestring
Returns string url
Remove a blob url
Parameters
urlstring
Create a new base64 encoded url
Parameters
contentanymimestring
Returns string url
Get type of an object
Parameters
objobject
Returns string type
Parse xml (or html) markup
Parameters
Returns document document
querySelector polyfill
Parameters
Returns element element
querySelectorAll polyfill
Parameters
Returns Array<element> elements
querySelector by property
Parameters
Returns Array<element> elements
Sprint through all text nodes in a document
Parameters
Create a treeWalker
Parameters
rootelement element to start withfuncfunction function to run on each elementfilter(function | object) function or object to filter with
Parameters
nodenodecallbackreturncallback false for continue,true for break inside callback
Convert a blob to a base64 encoded string
Parameters
blobBlog
Returns string
Creates a new pending promise and provides methods to resolve or reject it. From: https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Deferred#backwards_forwards_compatible
querySelector with filter by epub type
Parameters
Returns Array<element> elements
Find direct descendents of an element
Parameters
elelement
Returns Array<element> children
Find all parents (ancestors) of an element
Parameters
nodeelement
Returns Array<element> parents
Find all direct descendents of a specific type
Parameters
Returns Array<element> children
Filter all parents (ancestors) with tag name
Parameters
Returns Array<element> parents
Lightweight Polyfill for DOM Range