Skip to content Skip to sidebar Skip to footer

How Can I Programmatically Simulate Typing In A Contenteditable Html Element?

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()

Solution 1:

You could use Document.execCommand() with the insertTextcommand, 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: 0032px0rgba(0, 0, 0, .125);
  border-radius: 2px;
  min-height: 64px;
  padding: 16px;
  outline: none;
}
<divid="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.

Solution 2:

You can do something like this:

const element = document.querySelector('div');

const text = "This is my text";
var i = 0;

functiontype() {
    setTimeout(function() {
    element.textContent += text.charAt(i);
    i++;
    if (i < text.length) {
      type(); 
    }
  }, 500)
}

type();    
<divcontenteditable="true"></div>

It seems like an user is slowly typing in the div. You can tweak the speed by changing the 500 argument.

Solution 3:

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");

asyncfunctionmain() {
  let browser = await puppeteer.launch();
  let page = await browser.pages().then((pages) => pages[0]);
  await page.goto("https://google.com");
  await page.type('input[name="q"]', "Hello world :D", {
    delay: 50
  });
}

main();

Post a Comment for "How Can I Programmatically Simulate Typing In A Contenteditable Html Element?"