Search code examples
javascriptseleniummonitoringnewrelic

How to wait indefinitely till the page loads in javascript test case


I have a javascript performance monitoring synthetic script.I want to know if i can apply a statement to wait for the page to load since it has lot of redirection and takes time.

Currently using ...

$browser.sleep(80000);

I want to replace it with indefinite wait till page loads.


Solution

  • Yes, you can check/wait indefinitely until the page gets loaded with the help of JavaScript's window.onload.

    Try the below code which will check every 2 seconds and waits until the page gets loaded. Once the page is loaded then the loop will break otherwise it will run indefinitely :

    var status = false;
    window.sleep = function() { 
        return setTimeout(() => {
            console.log("=> Waited for 2 seconds...");
        }, 2000);
    }
    var getStatus = function() {
        for(var i = 0;; i++) {
            if(window.onload = function() {
                return true;
                }) {
                status = true;
                console.log(i+"). Loaded ? "+status);
                break;
            } else {
                console.log(i+"). Loaded ? "+status);
                sleep();
            }
        }
        return status;
    }
    getStatus();
    

    getStatus() will returns true once the page gets loaded successfully otherwise it won't return anything until the page gets loaded.