我想在尝试单击某个元素之前检测该元素是否为可点击。在我的特定用例中,在处理期间,该元素被其顶部的另一个元素隐藏,完成后,将移除叠加层,然后可以单击该元素。不幸的是,条件elementIsVisible
既不认为一个元素被另一个元素隐藏,也不认为一个元素的方法WebElement.isDisplayed
。
// find an element that is hidden behind some overlay
const hiddenElement = await driver.findElement(By.id('hiddenElement'));
// wait for element returns the "hidden" element
const await visibleElement = driver.wait(webdriver.until.elementIsVisible(hiddenElement));
// "isDisplayed" reports the "hidden" element as visible
const visible = await hiddenElement.isDisplayed();
我可以清楚地使用overlay元素来检测元素是否被隐藏,但这必须针对每种不同类型的overlay进行自定义,而我实际上是在寻找一种更通用的方法来检测元素是否真正可点击。
答案 0 :(得分:0)
我实际上确实找到了一种可以自己实现的解决方案,可以将其简化为以下内容:
函数isElementClickable
,负责检查元素是否可点击:
function isElementClickable(element) {
const SCRIPT = `
const element = arguments[0];
// is element visible by styles
const styles = window.getComputedStyle(element);
if (!(styles.visibility !== 'hidden' && styles.display !== 'none')) {
return false;
}
// is the element behind another element
const boundingRect = element.getBoundingClientRect();
// adjust coordinates to get more accurate results
const left = boundingRect.left + 1;
const right = boundingRect.right - 1;
const top = boundingRect.top + 1;
const bottom = boundingRect.bottom - 1;
if (document.elementFromPoint(left, top) !== element ||
document.elementFromPoint(right, top) !== element ||
document.elementFromPoint(left, bottom) !== element ||
document.elementFromPoint(right, bottom) !== element) {
return false;
}
return true;
`;
return element.getDriver().executeScript(SCRIPT, element);
}
函数'elementIsClickableCondition'可以代替webdriver.until.elementIsVisible
用作替换条件:
function elementIsClickableCondition(locator) {
return new webdriver.WebElementCondition('until element is visible', async function (driver) {
try {
// find the element(s)
const elements = await driver.findElements(locator);
if (elements.length > 1) {
throw new Error(`elementIsClickableCondition: the locator "${locator.toString()} identifies "${elements.length} instead of 1 element`);
} else if (elements.length < 1) {
return null;
}
const element = elements[0];
// basic check if the element is visible using the build-in functionality
if (!await element.isDisplayed()) {
return null;
}
// really check if the element is visible
const visible = await isElementClickable(element);
return visible ? element : null;
} catch (err) {
if (err instanceof webdriver.error.StaleElementReferenceError) {
return null;
} else {
throw err;
}
}
});
}