javascript - How to delete content from content-editable field on facebookmessenger.com? - Stack Overflow

时间: 2025-01-06 admin 业界

I am building a chrome extension that inserts text into the current text box.

I want to first delete all the text in the area and then insert the new text when the function is called. I have written some javascript code that works fine on many websites (such as /).

    focusedInputBox.focus();
    const range = document.createRange();
    range.selectNodeContents(focusedInputBox);
    const sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
    document.execCommand("delete");
    document.execCommand("insertText", false, newText);

The problem comes when I try to do this on /, which is the main usecase for this code. The exec command to insert text works but the one to delete doesn't do anything and fails with no errors. Instead the new text is pasted before the existing text, leading to lots of duplication.

This is what the HTML element there looks like

<div 
    aria-describedby=":rav:"
    aria-label="Message"
    class="xzsf02u x1a2a7pz x1n2onr6 x14wi4xw x1iyjqo2 x1gh3ibb xisnujt xeuugli x1odjw0f notranslate"
    contenteditable="true"
    role="textbox"
    spellcheck="true"
    tabindex="0"
    aria-placeholder="Aa"
    style="user-select: text; white-space: pre-wrap; word-break: break-word;"
    data-lexical-editor="true">
   <p class="xat24cr xdj266r"><br></p>
</div>

I have tried setting the text content with innerHtml and textContent but neither work to update it. Not sure how to debug this or delete the content as expected so anything would be helpful

最新文章