代码之家  ›  专栏  ›  技术社区  ›  rebornx

现在如何在梦魇动作evaluate_中使用等待功能?

  •  0
  • rebornx  · 技术社区  · 7 年前

    我在脚本中使用噩梦动作。在我正在使用evaluate\u now函数的操作中,如何在其中使用wait函数? this.wait('example')
    但是等待函数在 this.evaluate_now 作用

    Nightmare.action('example', function(done){
        this.evaluate_now(function() {
           //do some calculation and get element id
           var element = 'calculatedelement';
           activeTask.querySelector(element ).click();
           //I have to use the wait function here
        }        
        this.wait('body'); //wait is accessible here 
    });
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   F. Kauder    7 年前

    不能在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()的自定义操作仅限于执行一些同步指令,并且可能不适合您的用例。