2017-09-21 7 views
0

私はスクリプト内でナイトメアアクションを使用しています。私はevaluate_now関数を使用しているアクション内で、どのように私はそれで待機関数を使用することができますか? 私は、内部で待機機能を使用することができることを知っていますthis.wait('example')
しかし、待機機能はthis.evaluate_now機能の中でアクセス可能ではありません。内部の待機機能の使い方ナイトメアアクション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

あなたは(evaluate_now()内のアクションを使用して、待つことはできませんが)、ライブラリ(Source)でのアクションです。 evaluate_now()で提供されるコードは、電子インスタンス(Source)で実行されます。

代わりに、evaluate_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(); 
}); 

もう1つの方法は、カスタムアクションを呼び出す前にwait()関数を呼び出すことです。

Nightmare 
    .wait('#myComponent') 
    .example(); 

(evaluate_nowでそのカスタムアクションを覚えておいてください)、いくつかの同期の指示を行うことが限られており、多分あなたのユースケースに対応していません。

関連する問題