React构建的网站元素交互问题:无法聚焦到role为textbox的div元素
React构建的网站元素交互问题:无法聚焦到role为textbox的div元素
我现在在一个React构建的网站上,尝试聚焦到一个role="textbox"的div元素,但试了好几种方法都没成功。
我首先试了这段代码:
async function focusOnElement(selector) { let element = undefined; while (!element) { element = Array.from(document.querySelectorAll(selector)).at(-1); await delay(1000); } if (!element) { console.warn("Element not found for focusing."); return; } element.focus(); const focusEvent = new Event("focus", { bubbles: true, cancelable: true }); element.dispatchEvent(focusEvent); console.log(`Focused on element: ${selector}`); }
但完全没效果,于是我又试了这段试图触发React合成事件的代码:
async function focusOnElement(selector) { let element = undefined; while (!element) { element = Array.from(document.querySelectorAll(selector)).at(-1); await delay(1000); // Wait for the element to exist } if (!element) { console.warn("Element not found for focusing."); return; } // Focus on the element explicitly element.focus(); // Manually trigger React's synthetic focus event const reactKey = Object.keys(element).find( (key) => key.startsWith("_reactProps$") || key.startsWith("_reactFiber$") ); if (reactKey) { const props = element[reactKey]; if (props && props.onFocus) { // Dispatch a synthetic focus event that React can handle props.onFocus({ target: element, currentTarget: element, bubbles: true, cancelable: true, }); } } console.log(`Focused on element: ${selector}`); }
结果还是没法让目标div获得焦点。
补充一下场景:这个目标div出现在邮件规则设置的流程里,进入对应页面后,点击“添加新规则”,在条件里选择“发件人”,这个role为textbox的div就会显示出来,我就是要聚焦到这个元素上。
备注:内容来源于stack exchange,提问作者Shahroz Atiq
相关产品推荐
相关产品推荐

