0

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?

  • Get the position of the cursor (see https://stackoverflow.com/questions/7745867/how-do-you-get-the-cursor-position-in-a-textarea) and then insert your text at that index of the `.value` string. – Barmar Apr 17 '23 at 19:06
  • I don't want to get cursor position. I want to insert text on cursor position. `Instagram textarea don't show the default behavior.` – Mohit Saini Apr 17 '23 at 19:10
  • But if you get the cursor position you can insert there. E.g. if the cursor position is 5, you do `textField.value = textField.value.substring(0, 5) + text + textField.value.substring(5);` – Barmar Apr 17 '23 at 19:11
  • Simple `textField.value = "any text";` will NOT work in Instagram `textarea`. – Mohit Saini Apr 17 '23 at 19:14
  • I don't know instagram, but a textarea is a textarea. – Barmar Apr 17 '23 at 19:15

1 Answers1

1

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!");
Andrew
  • 630
  • 1
  • 5
  • 14
  • Sorry, But the code is NOT inserting any text (even if the `textarea` is empty). Any Suggestions... – Mohit Saini Apr 17 '23 at 19:25
  • 1
    @MohitSaini I don't know how you are testing. I open web version of Instagram -> go to chat -> F12 -> put cursor in the text area -> copy/paste code. It works. – Andrew Apr 17 '23 at 19:32
  • Did you noticed that the `send button` is NOT active even after text inserted, means you can't post that message. – Mohit Saini Apr 17 '23 at 19:36
  • Sorry, @Andrew It's my Mistake, The `textarea` needs to be recalculated every time we use insert text...thanks – Mohit Saini Apr 17 '23 at 19:44