0

I am trying to do a chrome extension that underlines specific words. Assume the user writes "hello" then I want to underline it. The thing that in Facebook and other social media the text field is a content editable div.

How can I access that text and manipulate only specific words inside it? I have tried doing this, but it didn't work

$('body').on('focus', '[contenteditable]', function() {
    const $this = $(this);
    $this.data('before', $this.html());
}).on('blur keyup paste input', '[contenteditable]', function() {
    const $this = $(this);
    if ($this.data('before') !== $this.html()) {
        $this.data('before', $this.html());
        $this.trigger('change');

    if ($this.text().includes("hello")){

        //document.execCommand('undeline'); //didn't work 
        //$this.style.textDecorationColor="red"; // neither did this
        //$this.style.textDecorationStyle="wavy";
    }
    }
});

Note: I have tried document.execCommand but it didn't give any results

Muhammad Dyas Yaskur
  • 6,914
  • 10
  • 48
  • 73
Rex
  • 147
  • 3
  • 11
  • check [this answer](https://stackoverflow.com/questions/3223682/change-css-of-selected-text-using-javascript) it might help you with the styling – Damian Dec 31 '19 at 11:19

1 Answers1

0

My pure JS solution:

    function logSelection(event) {
      const selection = window.getSelection().toString();
      const log = document.getElementById('log');
      console.log(selection, event); // debug

      // colors must be in hexadicemal (no #)
      const color = 'ff0000';
      const backColor = '0000ff';

      // apply css if you want
      this.style.textDecorationStyle="wavy";
      this.style.textDecorationColor='#'+color;

      document.execCommand('underline');
      document.execCommand('BackColor', false, '#' + backColor);
      document.execCommand('foreColor', false, color);
      //document.execCommand('HiliteColor', false, '#' + color); not working

      log.textContent = `You selected: ${selection}`;
    }

    const content = document.querySelector('div[contenteditable]');
    content.addEventListener('click', logSelection);

also you can take a look into the document.execCommand docs

Damian
  • 113
  • 8