Лучший грязный способ заполнения полей формы Я использую его при грязном браузерном тестировании форм
Адаптировано отсюда
(()=>{
const inputTypes = [
window.HTMLInputElement,
window.HTMLSelectElement,
window.HTMLTextAreaElement
];
const triggerInputChange = (selector,value)=>{
const node = document.querySelector(selector);
// only process the change on elements we know have a value setter in their constructor
if (inputTypes.indexOf(node.__proto__.constructor) > -1) {
const setValue = Object.getOwnPropertyDescriptor(node.__proto__, 'value').set;
let event = new Event('input',{
bubbles: true
});
if(node.__proto__.constructor === window.HTMLSelectElement){
event = new Event('change',{
bubbles: true
});
}
setValue.call(node, value);
node.dispatchEvent(event);
}
}
const formFields = [
['company', 'Shorts & Company'],
['first_name', 'McFirsty'],
['last_name', 'McLasty'],
['address1', '123 N. In The Woods'],
['city', 'Trunkborns'],
['state', 'WA'],
['zip', '55555']
];
formFields.forEach(field=>triggerInputChange(field[0], field[1]));
}
)()
Решение конкретного вопроса
document.querySelector('input').focus();
document.execCommand('insertText', false, 'Some Text For the Input');
Или, если вы хотите заменять текст каждый раз
document.querySelector('input').select();
document.execCommand('insertText', false, 'Some Text For the Input');
У меня есть скрипт Chrome dev tools -> sources -> scripts
, который я использую приделать грязные тесты форм
(()=>{
const fillText = (selector, value) => {
document.querySelector(selector).select();
document.execCommand('insertText', false, value);
}
const formFields = [
['[data-ref-name="company"]', 'My Company'],
['[data-ref-name="first_name"]', 'Styks']
]
formFields.forEach(field => fillText(field[0], field[1]));
}
)()