How to save and restore a selection range in javascript?

I want to save (serialize) the range Selectionfor reusing (deserializing) it in the next user session in iOSUIWebView applications .

Userpath

  • The user selects a portion of the text, click "Save"
  • Closes the built-in mobile browser
  • Opens the built-in mobile browser and sees the restored selection.

My idea is to first get the range, triggering window.getSelection().getRangeAt(0), and then save the properties startContainer, endContainer. Check out the following demo:

function saveSelectedRange() {  
  var highlightRange = window.getSelection().getRangeAt(0);
  
  var range = document.createRange();
  // ???
  console.log("start container: " + JSON.stringify(highlightRange.startContainer));
  console.log("end container: " + JSON.stringify(highlightRange.endContainer));

}
#intro {
    font-size: 125%;
    color: green;
}

p.small {
    font-size: 75%;
}

#content {
    margin-left: 330px;
}

#buttons {
    left: 10px;
    position: fixed;
    border: solid black 1px;
    background-color: background:#C0ED72;
    padding: 5px;
    width: 300px;
}

html.ie6 #buttons {
    position: absolute;
}

#buttons h3 {
    font-size: 125%;
    font-weight: bold;
    margin: 0;
    padding: 0.25em 0;
}
    <div id="buttons">
        <h3>Save selection range</h3>
        <p>Make a selection in the document and use the button below to save the selection range </p>
        <input type="button" ontouchstart="saveSelectedRange();" onclick="saveSelectedRange();" value="Save selection range">

    </div>

    <div id="content">
        <h1>Demo</h1>
        <p id="intro">
            Please use your mouse to make selections from the sample content and use the button
            on the left to save the selection range.
        </p>
</div>
Run codeHide result

, startContainer, endContainer , startOffset, endOffset . , ? ?

Ref: ,

+4
1

, @TimDown rangy-library .

var highlightRange = window.getSelection().getRangeAt(0);
var serializedRange = rangy.serializeRange(highlightRange);
var deseriazedRange = rangy.deserializeRange(serializedRange);

: Rangy RangyRange, - ( ), DOM Range, , rangy Native Range

0

Source: https://habr.com/ru/post/1655028/


All Articles