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.