我正在尝试编写一个 Chrome 扩展来自动填写 Jira 中的新问题,为了做到这一点,我需要从我的
react-select
控制一个 content_script
组件。这些确实是非常棘手的野兽,因为它们由许多 div 组成,其中有一个实际输入(通常是隐藏的,直到您单击它)。
我创建了一个小型的 codesandbox 演示,其中有一个基本的
react-select
示例和一个按钮,该按钮将焦点设置为输入并键入字母“Red”来过滤选项。我在那里设置了很多超时来减慢速度,以防我需要等待事情处理完毕才能输入(例如聚焦输入字段),但我的实验是徒劳的。
在我从 react-select site 复制的基本示例中,隐藏的输入字段始终位于 DOM 中(值得庆幸的是),但直到您单击它才出现在 Jira 中(唉!)。所以这将是另一个挑战,但即使在这个基本示例中,我什至无法让它工作。
是否可以像这样模拟用户点击和键盘事件,或者这种行为是否被视为潜在可疑并被浏览器故意阻止?我问的是不可能的事吗?
谢谢。
以下是如何在内容脚本中使用 JavaScript 来实现此目的的简化示例。这假设您已经将内容脚本注入到页面中并且可以访问 DOM:
// Function to simulate a click event
function simulateClick(element) {
const clickEvent = new MouseEvent('click', {
bubbles: true,
cancelable: true,
view: window,
});
element.dispatchEvent(clickEvent);
}
// Function to simulate typing into an input field
function simulateTyping(element, text) {
element.value = text;
const inputEvent = new Event('input', {
bubbles: true,
cancelable: true,
});
element.dispatchEvent(inputEvent);
}
// Assuming `reactSelect` is the react-select component
// Simulate click to make the input visible
simulateClick(reactSelect);
// Wait for the input to become visible (you might need to adjust the delay)
setTimeout(() => {
// Find the input field (adjust the selector as needed)
const inputField = document.querySelector('.react-select__input input');
// Simulate typing into the input field
simulateTyping(inputField, 'Red');
}, 1000); // Adjust the delay as needed
请记住,这是一个简化的示例,您可能需要根据 Jira 中反应选择组件的具体结构和行为进行调整。此外,请谨慎对待网站结构或行为的潜在变化,因为它可能会破坏您的自动化。