I am trying to create a Google Chrome extension where a user would highlight text on a page, and a happy face will appear at the beginning of the text. I have found this website where it demonstrates how to store and retrieve a range. My question is how do I get the start of the range to insert my < div id="happyFace">?
var selection = storeSelection(window.getSelection());
var selectionRange = restoreSelection(selection);
console.log( selectionRange.startContainer.offsetLeft ); //undefined
function makeXPath (node, currentPath) {
/* this should suffice in HTML documents for selectable nodes, XML with namespaces needs more code */
currentPath = currentPath || '';
switch (node.nodeType) {
case 3:
case 4:
return makeXPath(node.parentNode, 'text()[' + (document.evaluate('preceding-sibling::text()', node, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength + 1) + ']');
case 1:
return makeXPath(node.parentNode, node.nodeName + '[' + (document.evaluate('preceding-sibling::' + node.nodeName, node, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength + 1) + ']' + (currentPath ? '/' + currentPath : ''));
case 9:
return '/' + currentPath;
default:
return '';
}
}
function storeSelection (selectionObject) {
if (typeof window.getSelection != 'undefined') {
var selection = selectionObject;
var range = selection.getRangeAt(0);
if (range != null) {
selectionObject = makeXPath(range.startContainer) + '|' + range.startOffset + '|' + makeXPath(range.endContainer) + '|' + range.endOffset;
return selectionObject
}
}
}
function restoreSelection (selectionObject) {
var selectionDetails = selectionObject;
if (selectionDetails != null) {
selectionDetails = selectionDetails.split(/\|/g);
if (typeof window.getSelection != 'undefined') {
var range = document.createRange();
range.setStart(document.evaluate(selectionDetails[0], document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue, Number(selectionDetails[1]));
range.setEnd(document.evaluate(selectionDetails[2], document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue, Number(selectionDetails[3]));
return range;
}
}
}