How to detect the parent node of a window.getSelection ()?

0

I'm doing an extension for chrome that replaces the selected text on a page with templates predefined by the user.

In general it goes well, and it replaces the text in any part of the page, including the body of the Gmail messages, which was the original purpose, but when the selection is inside a textarea it does not work, I imagine that because the inside of a textarea is not part of the DOM itself.

How could I detect if the selected text is inside a textarea and in that case replace it in another way? Here the relevant code:

chrome.runtime.onMessage.addListener(
    function(request) {
        console.log("recibo");
        fill(request.texto);
    }
);

function fill(plant) {
    var mitext = window.getSelection()
    var res = plant.replace(/#/g, mitext);
    var sel, range;
    sel = window.getSelection();
    if (sel.rangeCount) {
        range = sel.getRangeAt(0);
        range.deleteContents();
        range.insertNode(document.createTextNode(res));
    }
}
    
asked by Montaycabe 30.05.2018 в 11:08
source

2 answers

1

I have already managed to discriminate if it is a textarea to act accordingly with document.activeElement I paste the final code:

function fill(plant) {
   var mitext = window.getSelection()
   var res = plant.replace(/#/g, mitext);
   var sel = window.getSelection();
   if (document.activeElement.tagName == "TEXTAREA") {
       $(document.activeElement).val(res);
   } else {
       if (sel.rangeCount) {
           var range = sel.getRangeAt(0);
           range.deleteContents();
           range.insertNode(document.createTextNode(res));
       }
   }
}
    
answered by 01.06.2018 в 15:08
0

I would start by writing

var textAreas = document.querySelectorAll('textarea')

then something like

textAreas.forEach(function (textArea) {
  if (textArea.value.indexOf(plantilla) != -1) { // la prueba
    textArea.style.color = 'red' // lo que quieras hacer aquí con textArea
  }
})

or in an onchange event for example:

var plantilla
document.querySelectorAll('textarea').forEach(function (textArea) {
  textArea.addEventListener('change', function () {
    if (this.value.indexOf(plantilla) != -1) { // la prueba
      this.style.color = 'red' // lo que quieras hacer aquí con textArea
    }
  })
})
    
answered by 01.06.2018 в 00:26