I am implementing a chrome extension that fills a form basically.
This form has ProseMirror rich text editor in it.
I want to trigger Ctrl+V or paste operation on the text editor, but I couldn’t find any solution to this. these are the things I’ve tried so far:
let el = document.querySelector('[contenteditable="true"]')
el.focus()
navigator.clipboard.readText().then((clipText) => {
// el.innerText = clipText doesn't work
// el.innerHTML = clipText doesnt't work
// this.document.execCommand("insertText", false, clipText) doesnt work
})
document.dispatchEvent(new KeyboardEvent({key:'V', ctrlKey: true})) // doesnt work
When I do the pasting operation manually, the prose mirror component automatically converts it to a pretty table.
If you want to try -> copy a table then paste it here https://prosemirror-tables.netlify.app/
How do I trigger the paste event so it would look like as expected case?
Eventhough, this case is related to prose mirror, we may consider this problem for other rich text editors as well.
If I just copy an image and paste it into a rich text editor, picture will be uploaded but it won't work If I try to paste it programmatically
I've tested the following code in Chromium 107.0.5304.121 (Official Build) Arch Linux (64-Bit), and it does what you require.
Notes:
document.execCommand("paste")
doesn't paste the clipboard contents, and returns false.element.focus();
is necessary.manifest.json
{
"manifest_version": 3,
"name": "Paste",
"version": "1.0",
"action": {
},
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["content_script.js"]
}
],
"permissions": [ "clipboardRead" ]
}
background.js
console.log("background.js");
content_script.js
let element = document.querySelector('[contenteditable="true"]');
if (element) {
console.log("element.hasChildNodes()", element.hasChildNodes());
while (element.hasChildNodes()) {
element.removeChild(element.lastChild)
}
element.focus();
setTimeout(() => {
let result = document.execCommand("paste");
console.log("result", result);
}, 0);
}
else {
console.log('No elements with contenteditable="true"');
}