2

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?

Select text in javascript

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.

Get page selection including HTML?

Community
  • 1
  • 1
far_see
  • 21
  • 3
  • 1
    Start with this http://stackoverflow.com/a/14351458/1507998 – rsanchez May 08 '15 at 04:16
  • possible duplicate of [Creating a chrome extension which takes highlighted text on the page and inserts it into a textarea in popup.html](http://stackoverflow.com/questions/14349263/creating-a-chrome-extension-which-takes-highlighted-text-on-the-page-and-inserts) – Xan May 08 '15 at 10:40

0 Answers0