Dynamically write text in Facebook textbox using JavaScript

I was recently creating a Chrome extension named Butler-AI that allows using the ChatGPT on any website by typing a simple command and during that time found that it is not easy to update the textbox of Facebook using JavaScript.

After digging up the web, I came up with a solution and it works like a charm.

If you inspect the text area where you write anything for the post, you will find that Facebook uses a div with the attribute role="textbox" and contenteditable="true", inside this there is a p tag and a br.

Facebook textbox inspected elements

The moment you start typing the br is replaced with a <span data-lexical-text="true">hellow</span>.

Thus we have to update the value in this span and after that trigger an input event from the parent of this span that is from the div[role="textbox"] to make the update.

function facebookUpdate(actEl, text) {
  if (document.body.parentElement.id == "facebook") {
    var dc = getDeepestChild(actEl);
    var elementToDispatchEventFrom = dc.parentElement;
    let newEl;
    if (dc.nodeName.toLowerCase() == "br") {
      // attempt to paste into empty messenger field
      // by creating new element and setting it's value
      newEl = document.createElement("span");
      newEl.setAttribute("data-lexical-text", "true");
      dc.parentElement.appendChild(newEl);
      newEl.innerText = text;
    } else {
      // attempt to paste into not empty messenger field
      // by changing existing content
      dc.textContent = text;
      elementToDispatchEventFrom = elementToDispatchEventFrom.parentElement;
    }
    // simulate user's input
    elementToDispatchEventFrom.dispatchEvent(new InputEvent("input", { bubbles: true }));
    // remove new element if it exists
    // otherwise there will be two of them after
    // Facebook adds it itself!
    if (newEl) newEl.remove();
  }
}

// helper function
function getDeepestChild(element) {
  if (element.lastChild) {
    return getDeepestChild(element.lastChild);
  } else {
    return element;
  }
}

Here we have to pass the text area and the text and it will dynamically update the text in the Facebook text box, works with the messenger as well.

facebookUpdate(document.querySelector('[role="textbox"]'), "Hello World!");

or

facebookUpdate(document.querySelector('.notranslate'), "Hello World!");