Get highlighted text in JavaScript
<p>There are plenty of answers on stackoverflow.
I used this code:</p>

<pre><code>function getSelectedText() {
    var text = "";
    var activeEl = document.activeElement;
    var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;
    if (
      (activeElTagName == "textarea" || activeElTagName == "input") &amp;&amp;
      /^(?:text|search|password|tel|url)$/i.test(activeEl.type) &amp;&amp;
      (typeof activeEl.selectionStart == "number")
    ) {
        text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);
    }else if (window.getSelection) {
        text = window.getSelection().toString();
    }else if (document.selection) {
        return document.selection.createRange().text;
    }
    return text;
}
</code></pre>

<p>It works good on many sites, but on many sites, where code is generated on the fly (using react), like udacity, above function gives empty text.</p>

<p>It occurs when I select text inside code window in on of the udacity courses.</p>

<p>Why above function returns empty text and what is a workaround?</p>

<p>Thanks in advance.</p>