更好的填写表单字段的脏方法
我在对表单进行脏浏览器测试时使用它
Adapted from Here
(()=>{
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]));
}
)()