Trying to update the text of a tweet or dynamically write a new tweet through JavaScript, by editing the text content of the HTML element but the text vanishes as soon it gets focus.
Let us see how we can dynamically update the tweet value. The text area of twitter where we write the tweet is a div
with all the ALLY attributes which makes it editable.
Inside the div once you start writing you will see a span
element with the attribute data-text="true"
, this is the element whoes text content we have to change.
But after changing the content, we have to get it parent element i.e the span
with the attribute data-offset-key="cac98-0-0"
and trigger an input event from it to notify that there has been an input or change in the text.
Because the data-offset-key="cac98-0-0"
keeps changing but data-text="true"
remains constant, we will use this data-text="true"
as a selector and then get its parent element.
function twitterUpdate(text) {
const parentEle = document.querySelector('[data-text="true"]')?.parentElement;
if (parentEle) {
parentEle.innerHTML = `${text}`;
parentEle.dispatchEvent(new Event("input", { bubbles: true, cancelable: true }));
}
}
This will dynamically update the text in the twitter textbox through javascript. Works on the normal as well as the reply textbox.