From 205b829092a22a47d811a19fc1b5ab7f756eaedb Mon Sep 17 00:00:00 2001 From: Pengyu Chen Date: Fri, 19 Oct 2018 00:01:03 +0100 Subject: [PATCH] Added: Userspace example of waiting for a specific condition. --- docs/scripting-ref.rst | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/docs/scripting-ref.rst b/docs/scripting-ref.rst index 224707a2c..c98e7d7c7 100644 --- a/docs/scripting-ref.rst +++ b/docs/scripting-ref.rst @@ -419,6 +419,48 @@ time after each page load in case of redirects: return nil, "too_many_redirects" end +It's also common practice to wait for a specific condition, other than a fixed +amount of time: + +.. code-block:: lua + + function wait_until(splash, timeout, polling_interval, check_func, ...) + -- XXX: Assuming the check function is fast enouch, as the time is not being counted. + local total_waited = 0 + while total_waited < timeout do + local ok, reason = splash:wait(polling_interval) + if not ok then + return ok, string.format('wait failed: %s', reason) + end + local check_result = check_func(...) + if check_result then + return true, check_result + end + total_waited = total_waited + polling_interval + end + return nil, 'timeout exceeded' + end + + function main(splash) + -- Goto example.com and wait for a specific node to be loaded in the DOM + splash:go('http://example.com') + wait_until(splash, 10, 0.1, splash.select, splash, 'div#example_selector') + + -- Goto example.com and wait for a specific response to be downloaded + local example_response_downloaded = false + splash:on_response(function (response) + if string.find(response.url, 'specific_url_pattern_here') then + example_response_downloaded = true + end + end) + splash:go('http://example.com') + wait_until( + splash, 10, 0.1, + function () + return example_response_downloaded + end + ) + end .. _splash-jsfunc: