如何使用Javascript点击页面中属性相同的指定按钮(Chrome扩展场景)
解决方案
方案1:按按钮文本精准定位(推荐)
两个按钮的核心差异为内部展示文本不同,可通过XPath直接匹配对应文本的按钮,不会受选中状态、类名变化影响:
// 点击文本为「The App」的按钮 const targetXpath = "//button[text()='The App']"; const targetBtn = document.evaluate(targetXpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; // 点击前判断按钮存在且未被禁用 if (targetBtn && !targetBtn.disabled) { targetBtn.click(); }
如果需要点击文本为「NTC App」的按钮,仅需将XPath中的文本内容替换为NTC App即可。
方案2:按选中状态定位
如果你的需求是点击当前处于选中状态的按钮,可直接匹配按钮的selected类:
const selectedBtn = document.querySelector('button.ng-binding.selected'); if (selectedBtn && !selectedBtn.disabled) { selectedBtn.click(); }
Angular事件兼容触发
如果直接调用click()方法未触发ng-click绑定的业务逻辑,可手动派发原生鼠标事件:
if (targetBtn) { const clickEvent = new MouseEvent('click', { bubbles: true, cancelable: true, view: window }); targetBtn.dispatchEvent(clickEvent); }
内容的提问来源于stack exchange,提问作者Mehditation
相关产品推荐
相关产品推荐

