I am trying to programmatically insert strings into text fields. I tried document.execCommand("insertText", false, wordToInsert);
But it does not work on few sites which are using draft.js editor e.g Facebook. Sometimes it behaves unexpectedly e.g after inserting the text, backspace or enter key doesn't work. So after researching SO, I ended up with a solution of dispatching a paste event as shown in the code snippets below.
const target = document.querySelector('[contenteditable="true"]');
target.addEventListener('paste', (event) => {
console.log('Paste event caught!');
console.log('Clipboard data:', event.clipboardData.getData('text/plain'));
});
const dataTransfer = new DataTransfer();
dataTransfer.setData('text/plain', 'hello');
target.dispatchEvent(
new ClipboardEvent('paste', {
clipboardData: dataTransfer,
bubbles: true,
cancelable: true,
})
);
dataTransfer.clearData();
Now above code works on draft.js demo site but does not work on my simple test site. You can test this code by simply opening those sites and pasting it on the console.
Note: I am looking for a simple universal insertText function that can work on any site's input, textarea or content-editable fields.