Enter Data into a Custom-Handled Input Field

Enter data into a custom-handled input field

There is a built-in DOM method document.execCommand.

In case of an extension, use this code in the content script.

// some.selector may be `input` or `[contenteditable]` for richly formatted inputs
const el = document.querySelector('some.selector');
el.focus();
document.execCommand('insertText', false, 'new text');
el.dispatchEvent(new Event('change', {bubbles: true})); // usually not needed

It imitates physical user input into the currently focused DOM element so all the necessary events will be fired (like beforeinput, input) with isTrusted field set to true. On some pages the change event should be additionally dispatched as shown above.

You may want to select the current text to replace it entirely instead of appending:

replaceValue('some.selector', 'new text');

function replaceValue(selector, value) {
const el = document.querySelector(selector);
if (el) {
el.focus();
el.select();
if (!document.execCommand('insertText', false, value)) {
// Fallback for Firefox: just replace the value
el.value = 'new text';
}
el.dispatchEvent(new Event('change', {bubbles: true})); // usually not needed
}
return el;
}

Note that despite execCommand being marked as obsolete in 2020, it'll work in the foreseeable future because a new editing API specification is not finished yet, and knowing how slow such things usually move it may take another 5-20 years.

Chrome extension how to enter text in any selected text field

Thanks to the answer of wOxxOm, with a bit of modification, I got it to work. This is my final code:

//Nickname gets generated here
//...

const keyboardEventInit = {bubbles:false, cancelable:false, composed:false, key:'', code:'', location:0};
const element = document.activeElement;

if (element) {

element.dispatchEvent(new KeyboardEvent("keydown", keyboardEventInit));
element.value = nick;
element.dispatchEvent(new KeyboardEvent("keyup", keyboardEventInit));
element.dispatchEvent(new Event('change', {bubbles: true}));

}

Javascript - press enter key after updating input value

I think you correctly saw the issue; you are trying to dispatch keydown event inside a keydown listener which would end in an infinite loop.

If you want to dispatch a keydown event after the value is updated programmatically, you should put the dispatch line after the value change line:

document.querySelectorAll("input[type='number']")[index].value = 5;
el.dispatchEvent(new Event('keydown'));

If you are not the one triggering the change of value, it is a bit different (and more complicated). Here are question 1 and question 2 that address that exact issue.



Related Topics



Leave a reply



Submit