I am having trouble understanding the code (I am new to JS) and most codes don't work for me. I am building a Chrome Extension to display text selection on a webpage inside a popup. But the text selection does not display in console. Moreover, I need to preserve formatting of the selected text and display it inside popup.html.
popup.html
<html>
<head>
</head>
<body>
<script src="jquery-1.11.3.min.js"></script>
<script src="popup.js"></script>
<div contenteditable="true" id="para">Some text</div>
</body>
</html>
popup.js
window.onload=getSelectionHtml;
function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
console.log(html);
return html;
}
I tried setting up a breakpoint on the second if statement but even after I select text the value sel.rangeCount did not change (it remains zero) and the if clause does not execute.
Similar answers on Stackoverflow
Uncaught IndexSizeError: Failed to execute 'getRangeAt' on 'Selection': 0 is not a valid index
Chrome doesn't get the selected html string wrapping tags (contenteditable)
Get page selection including HTML?
Determine which DOM elements the current text selection contains
Get elements in text selection
How to copy formatting from the selected text?
This code was taken from
Chrome doesn't get the selected html string wrapping tags (contenteditable)
I almost forgot!
Intuitively, I think what I am looking for might already have been answered here (quoted above). I tried this too, and downloaded the chrome-extension uploaded by Arne Roomann-Kurrik and it did not help.