不能在evaluate\u now()中使用动作,而wait()是库中的动作(
Source
). evaluate\u now()中提供的代码在electron实例中执行(
Source
).
相反,您可以在evaluate\u now()的回调函数中使用setTimeout()函数来创建等待。下一个示例是一个检查元素在视口中是否可见的操作。
Nightmare.action('waitInViewport', function (selector, done) {
// Keep evaluation function in a variable
const evalFn = () => {
this.evaluate_now((selector) => {
const element = document.querySelector(selector);
if (!element) {
return false;
}
const rect = element.getBoundingClientRect();
const height = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
const width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
return !(rect.top >= height || rect.bottom <= 0 ||
rect.left >= width || rect.right <= 0);
}, (err, isVisible) => {
if (err) {
return done(err);
}
if (isVisible) {
return done(null, isVisible);
}
// If we are here, so we didn't found the element, so just run another evaluation after a delay
setTimeout(evalFn, 500);
}, selector);
};
// Don't forget to do the first call of the evaluation
evalFn();
});
另一种方法是在调用自定义操作之前调用wait()函数。
Nightmare
.wait('#myComponent')
.example();
请记住,evaluate\u now()的自定义操作仅限于执行一些同步指令,并且可能不适合您的用例。