Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Special Case: Unable to insert text in textarea on cursor position in Browser using JavaScript

I want to insert text in Instagram Chat textarea using javascript

Instagram textarea(in messages tab) can be accessed by using….

const textArea = document.getElementsByClassName("_ab5y")[0].getElementsByClassName("_acrb")[0].children[1].getElementsByTagName("textarea")[0];

the value can be inserted easily using…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    function setKeywordText(text) {
        textArea.value = text;
        var evt = document.createEvent("Events");
        evt.initEvent("input", true, true);
        textArea.dispatchEvent(evt);
    }

    setKeywordText("Hello!");

But, Unable to Insert text on cursor position.

Note-
1. I know that initEvent is deprecated. But alternative is NOT working.
2. I don’t want to change value (like- append text as string and then, change whole to the textarea).

Is there any way to do this?

>Solution :

Tested on Instagram, this code can insert text in the cursor position.

const textArea = document.getElementsByClassName("_ab5y")[0].getElementsByClassName("_acrb")[0].children[1].getElementsByTagName("textarea")[0];

function setKeywordText(text) {
  const startPos = textArea.selectionStart;
  const endPos = textArea.selectionEnd;
  const messageStart = textArea.value.substring(0, startPos);
  const messageEnd = textArea.value.substring(endPos, textArea.value.length);
  textArea.value = messageStart + text + messageEnd;
  textArea.setSelectionRange(startPos + text.length, startPos + text.length);
}

setKeywordText("Hello!");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading