Search code examples
javascripteventstextareainstagram

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...

    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!");