我正在尝试创建一个 Chrome 扩展程序,当用户单击按钮时,该扩展程序可以自动将文本输入到文本框中。我尝试过不同的方法,例如使用innerHTML和textContent,但我想知道是否有一个专门为更新DOM中的文本而设计的函数,我可以在单击按钮时使用它。尽管尝试了诸如innerHTML和textContent之类的各种方法,但我在使用div元素上的querySelector应用更新时遇到了问题。单击按钮后是否可以调用任何函数来更有效地实现此目的?
const PasteMessage = async (el, text) => {
// Get current content of the element
const currentContent = el.textContent;
// Append new text with a space if there's existing content
const newText = currentContent ? " " + text : text;
// Create a new DataTransfer object and set itenter code heres data to
the newText
const dataTransfer = new DataTransfer();
dataTransfer.setData("text", newText);
// Create a new ClipboardEvent with the dataTransfer object
const event = new ClipboardEvent("paste", {
clipboardData: dataTransfer,
bubbles: true,
});
// Focus the element
el.focus();
// Wait for a short period to ensure the element is focused
await sleep(50);
// Dispatch the paste event to the element
el.dispatchEvent(event);
// Wait for the pasted data to be processed and return the result
return await waitForPastedData(el, el.childNodes.length);
};