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.

Share Improve this question edited Apr 2, 2021 at 17:21 Penguin asked May 3, 2020 at 5:05 PenguinPenguin 4114 silver badges16 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

You 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