Я хочу сэкономить (сериализую) диапазон Selection
, чтобы повторно использовать (десериализировать) его в следующей пользовательской сессии в моем UIWebView
Приложение iOS.Как сохранить и восстановить диапазон выбора в javascript?
UserPath:
- Пользователя выбирает часть текста, нажмите кнопку Сохранить
- Замыкает встроенный в мобильном браузере
- открывает встроенный в мобильном браузере и видит восстановленный выбор.
Моя идея заключается в том, во-первых получить диапазон, вызвав window.getSelection().getRangeAt(0)
, а затем сохранить его startContainer
, endContainer
свойства. Проверьте следующее демо фрагмент:
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>
Как вы видите, консольные журналы опорожнить startContainer
, endContainer
значения, но startOffset
, endOffset
свойства ок. Какие значения нужно сохранить, чтобы иметь возможность восстанавливать диапазон выбора в последующих сеансах? Каковы общие способы его достижения?
Ref: Range class, Selection class