[英]Filling a react form from the Google Chrome console
我一直在嘗試編寫一種通過將腳本復制並粘貼到Chrome控制台中來自動完成網站上某些表格的程序。 (沒有違法行為。)但是,問題在於該網站是用React編寫的,這意味着它們用於表單的受控組件會干擾簡單的form.value
更改。 如果我嘗試使用類似於form.value = answer
的形式填充表單,則仍需要對表單進行手動按鍵操作才能使其正常工作,這不適合我的自動化需求。
到目前為止我嘗試過的是:
-填寫form.value
然后觸發form.value
/ keydown / keyup。
-填寫form.value
減去一個字母,然后觸發一個按鍵,對應於錯過的字母。
之后,由於某些奇怪的原因,在執行手動按鍵之前,Enter鍵也無法提交。
誰能幫我嗎? 謝謝!
填寫表單字段的更好的骯臟方式我在對表單進行臟瀏覽器測試時會使用此方法
(()=>{
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
在對表單進行臟測試時使用的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]));
}
)()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.