admin管理员组文章数量:1405170
I need to simulate the interaction of a user typing into a contenteditable
HTML element programmatically.
I cannot use things such as HTMLElement.onkeypress()
or HTMLElement.fire()
.
I cannot modify the actual code or content of the element using element.innerHTML
or element.textContent
, I need a way to simulate it.
I need to simulate the interaction of a user typing into a contenteditable
HTML element programmatically.
I cannot use things such as HTMLElement.onkeypress()
or HTMLElement.fire()
.
I cannot modify the actual code or content of the element using element.innerHTML
or element.textContent
, I need a way to simulate it.
3 Answers
Reset to default 5You could use Document.execCommand()
with the insertText
mand, which will also fire input
events automatically:
const editor = document.getElementById('editor');
editor.oninput = (e) => console.log('Input');
setTimeout(() => {
editor.focus();
document.execCommand('insertText', false, 'Inserted text...\n\n');
}, 1000);
body {
display: flex;
flex-direction: column;
font-family: monospace;
}
#editor {
box-shadow: 0 0 32px 0 rgba(0, 0, 0, .125);
border-radius: 2px;
min-height: 64px;
padding: 16px;
outline: none;
}
<div id="editor" contenteditable="true"></div>
However, note that's currently obsolete and even before it was inconsistent across different browser (same as contenteditable
):
Obsolete
This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.
You can do something like this:
const element = document.querySelector('div');
const text = "This is my text";
var i = 0;
function type() {
setTimeout(function() {
element.textContent += text.charAt(i);
i++;
if (i < text.length) {
type();
}
}, 500)
}
type();
<div contenteditable="true"></div>
It seems like an user is slowly typing in the div. You can tweak the speed by changing the 500
argument.
If you just need to simulate a user's input, you can use scriptable browsers like puppeteer. It is a nodejs package, it gives you a browser that you can control from your code, and it has exactly the thing you need. You can even control the speed of typing, etc.
Here is a sample code that opens a google page and enters the text "Hello world :D" in the search box
const puppeteer = require("puppeteer");
async function main() {
let browser = await puppeteer.launch();
let page = await browser.pages().then((pages) => pages[0]);
await page.goto("https://google.");
await page.type('input[name="q"]', "Hello world :D", {
delay: 50
});
}
main();
本文标签: javascriptHow can I programmatically simulate typing in a contenteditable HTML elementStack Overflow
版权声明:本文标题:javascript - How can I programmatically simulate typing in a contenteditable HTML element? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744279083a2598563.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论