I have trouble restoring selected text with javascript When the user selects some text from page A with the mouse. That selection is saved in localStorage.
I was able to store the selected string. I intend to restore the selection using
$(window).on("load", function () {
restoreSelection();
});
However, I cannot restore that string. Here is my code. Any help would be appreciated.
$(".main").mouseup(function () {
var range, sel;
var colour = 'yellow';
if (window.getSelection) {
// IE9 and non-IE
try {
if (!document.execCommand("BackColor", false, colour)) {
makeEditableAndHighlight();
}
} catch (ex) {
makeEditableAndHighlight()
}
}
});
function makeEditableAndHighlight() {
var colour = 'yellow';
var range, sel = window.getSelection();
if (sel.rangeCount && sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
// Use HiliteColor since some browsers apply BackColor to the whole block
if (!document.execCommand("HiliteColor", false, colour)) {
document.execCommand("BackColor", false, colour);
}
document.designMode = "off";
saveSelections(sel);
}
function saveSelections(selection) {
if(selection){
var highlight = selection.toString();
// localStorage.setItem('textSelection', highlight);
}
}
function restoreSelection() {
//var highlight = localStorage.getItem('textSelection');
if (highlight) {
//I am stumped here I have tried
//CreateRange() but nothing works
}
}
div.storyText * ::selection {
background: #FFFF00; /* WebKit/Blink Browsers */
}
div.storyText * ::-moz-selection {
background: #FFFF00; /* Gecko Browsers */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main ">
<p>Blalalalalalalalalalalalalala lorem ipsum text textstsetew </p>
</div>
Does anyone have any idea? Thanks