From e274e9f733cab098b59ec98b154fab7e54d19d56 Mon Sep 17 00:00:00 2001 From: Robert Jones Date: Fri, 15 Feb 2013 19:45:24 +0000 Subject: [PATCH] Add waitForNthSelector. --- lib/webpage.js | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/lib/webpage.js b/lib/webpage.js index 84f05d5..64d531a 100644 --- a/lib/webpage.js +++ b/lib/webpage.js @@ -298,6 +298,41 @@ setTimeout(testForSelector, timeoutInterval); }, + //waits for selector to appear, then executes callbackFn + waitForNthSelector:function (selector, count, callbackFn, timeout) { + var self = this, + startTime = Date.now(), + timeoutInterval = 150, + testRunning = false, + //if evaluate succeeds, invokes callback w/ true, if timeout, + // invokes w/ false, otherwise just exits + testForSelector = function () { + + var elapsedTime = Date.now() - startTime; + + if (elapsedTime > timeout) { + self.options.debug && console.log('warning: timeout occurred while waiting for selector:"%s"'.yellow, selector); + callbackFn(false); + return; + } + + self.evaluate(function (selectorToEvaluate) { + return document.querySelectorAll(selectorToEvaluate).length; + }, function (result) { + testRunning = false; + if (result >= count) {//selector found + callbackFn(true); + } + else { + setTimeout(testForSelector, timeoutInterval); + } + }, selector); + }; + + timeout = timeout || 10000; //default timeout is 2 sec; + setTimeout(testForSelector, timeoutInterval); + }, + injectJs:function (filename, callbackFn) { executeMethod.call(this, '/page/functions/injectJs', callbackFn, filename);