Search code examples
javagoogle-chromeselenium-webdriverselenium-chromedriverchrome-web-driver

Avoid the execution stop while browsing in Selenium WebDriver


I need help for this thing that's driving me crazy. I want to check the browser url in and endless loop, waiting a little (Thread.Sleep) between a loop and another, to not overload the CPU. Then, if the browser url is what I need, I want to add/change/remove an element through Javascript before the page is fully loaded, otherwise the person who uses this could see the change. (I don't need help for the javascript part) But there's a problem: it seems that in Selenium Webdriver when I navigate to a page (with .get(), .navigate().to() or also directly from the client) the execution is forced to stop until the page is loaded. I tried to set a "fake" timeout, but (at least in Chrome) when it catches the TimeoutException, the page stops loading. I know that in Firefox there's an option for unstable loading, but I don't want to use it because my program isn't only for Firefox.

public static void main(String[] args) throws InterruptedException {        
    System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.manage().timeouts().pageLoadTimeout(0, TimeUnit.MILLISECONDS); // Fake timeout
    while (true) {
        try {
            // If the url (driver.getCurrentUrl()) is what I want, then execute javascript without needing that page is fully loaded
            // ...
            // ...               
        }
        catch (TimeoutException e) {
             // It ignores the Exception, but unfortunately the page stops loading.
        }
        Thread.sleep(500); // Then wait some time to not overload the cpu
    }
}

I need to do this in Chrome, and if possible with Firefox and Internet Explorer. I'm programming in Java. Thanks in advance.


Solution

  • Selenium is designed to stop once the webpage is loaded into the browser so that it can proceed with execution.

    In your case there are two options:

    1) If the browser url will change automatically (ajax) at an arbitrary time, then just keep getting browser url until your condition satisfies.

    while(currentURL.equals("Your Condition")){
      currentURL = driver.getCurrentUrl();
      Thread.sleep(2000);
    }
    

    2) If the browser needs to be refreshed use the refresh method in a loop until you get your desired url

    while(currentURL.equals("Your Condition")){
        driver.navigate().refresh();
        currentURL = 
        Thread.sleep(2000);
    }