I am developing epub reader for ios and android. I want to implement text highlights and add note function to my epub reader. And I want to know how to these functionality for fixed layout epub. I can get selected object by javascript:window.getSelection()
. I want to save and retrieve these objects for future use. Here the code I used for highlighting and saving text:
var selection;
var storedSelections[];
function highlightText() {
if (window.getSelection) {
selection = window.getSelection();
}
if (selection.rangeCount > 0) {
var range = selection.getRangeAt(0);
var selectedText = range.toString();
var span = document.createElement("span");
span.id = "span_" + range.startOffset + "_" + range.endOffset ;
alert(span.id);
span.onclick = function() {
myOnclikFunction(selectedText);};
span.setAttribute("class","uiWebviewHighlight");
span.style.backgroundColor = "skyblue";
range.surroundContents(span);
selection.removeAllRanges();
selection.addRange(range);
for (var i = 0; i < selection.rangeCount; i++) {
storedSelections.push (selection.getRangeAt (i));
}
selection.removeAllRanges();
localStorage.setItem('storedSelections',storedSelections);
}}
I used this code for retrieve highlighted text:
function ShowStoredSelections () {
storedSelections.length=0;
var retrieved= localStorage.getItem('storedSelections');
storedSelections.push (retrieved);
var selection = window.getSelection ();
for (var i = 0; i < storedSelections.length; i++) {
selection.removeAllRanges ();
selection.addRange (storedSelections[i]);
if (selection.rangeCount > 0) {
var range = selection.getRangeAt(0);
var selectedText = range.toString();
var span = document.createElement("span");
span.id = "span_" + range.startOffset + "_" + range.endOffset ;
span.onclick = function() {
myOnclikFunction(selectedText);
};
span.setAttribute("class","uiWebviewHighlight");
span.style.backgroundColor = "red";
range.surroundContents(span);
selection.removeAllRanges();
selection.addRange(range);
}
}}
I can't add retrieved text to selection.addRange
. What am I doing wrong in this?
Please give me some ideas or suggestions to overcome this problem.
Thanks in advance for any reply or answer.
I have implemented all these for native epub player of androd and iOS- its a product R&D for an organisation
Instead of using getSelection follow the below steps.Its tedious but functionality would be fully under your control
-> Give url to UIWebView (iOS) or WebView (android)
-> in call back of webview didload - wrap all text words into spans with unique ids
-> propagate touch events to webview- javascript will handle those touches using
function onTouchMove(e)
-> get touched span using
document.elementFromPoint
-> highlight those spans (words) -> You will get position of each span
$('#wordID-'+sWordID).position()
,you can pass those values from javascript to native code-> Add sticky notes view to the super view of webview
Note: better inject jQuery in run time into webview for wrapping words into spans