johnfactotum / foliate-js

Render e-books in the browser
https://johnfactotum.github.io/foliate-js/reader.html
MIT License
418 stars 60 forks source link

How to retrieve the selection range/CFI from "onselectionchange"? #30

Open nigini opened 3 months ago

nigini commented 3 months ago

Hey there. Thanks for developing this library.

I am very interested in replicating some Annotation features from Foliate into the foliate-js demo, so I can read books on my Android device.

The first step is obviously to be able to retrieve the selection from the document and get the CFI range. I have added the following to the Reader.onLoad():

doc.addEventListener('selectionchange', this.#onselect.bind(this))
//Where onselect is:
#onselect(range) {
        let selection = window.getSelection()
        console.log("Selection", selection)
        console.log("Range", range)
}

But neither the selection nor range seem to give me specific enough targets to work with. Hope you can help me.

johnfactotum commented 3 months ago

The book is rendered in an iframe, so you need to use something like event.currentTarget.defaultView.getSelection().