-1

I'm writing an chrome extension, and I want to pick up selected text in code sections of tech.io, like this one: https://prnt.sc/hhfkwu on https://tech.io/playgrounds/347/javascript-promises-mastering-the-asynchronous/what-is-asynchronous-in-javascript

I have this function which works pretty much on any other website, but it doesn't work correctly here, it returns empty string or some weird unicode character:

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

How should I alter it in order to work on this particular code section on tech.io website?

kecman
  • 813
  • 3
  • 14
  • 34

1 Answers1

0

The problem is Ace Editor. While it looks like your selecting text in that box, it's actually drawing boxes that look like selections, in order to properly format the colors underneath.

window.getSelection will yield nothing because no selection actually exists.

You'll likely need to check document.activeElement to see if it's an ace editor, and then use the solution from this answer:

It's better to use editor.getSelectedText() instead.

Blue
  • 22,608
  • 7
  • 62
  • 92
  • Thanks for feedback, but how do I get reference to editor? I assume I have to load `ace.js` as a content-script, but what next? – kecman Nov 30 '17 at 20:52
  • OK got it, I get a ref to `editor` using this code `editor = ace.edit(aceEditorElement);`, and I'm able to get the selected text after that, but it messes the layout of editor, it looks like this now: https://prnt.sc/hhg7m6 – kecman Nov 30 '17 at 21:18
  • Edit your original question, and post an updated answer, and we can assist further @kecman – Blue Dec 01 '17 at 13:26