Search code examples
javaseleniumhandlewindow-handles

Waiting for one browser to complete action and continue in another browser in selenium webdriver


Scenario

I have two applications one is my main order placement website and another coupon generation site . In between my order placement scenario, I have to open a new browser window with a completely new user agent and other settings and create a coupon, grab coupon value and come back to the previous window and apply the coupon.

Sample Code :

WebDriver driver2 = new FirefoxDriver();
driver2.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver2.get("URL");
driver.get(URL);
System.out.println(URL);

Solution

  • If I understood correctly, your problem was making the first webdriverwait until the second one is finished getting the coupon code.

    For this my suggestion would be using threads and make the first one wait for the second one to finish.

    Here is your Thread class. What it will do will fall under the run() method.

    class ThreadDemo extends Thread {
        private Thread t;
        private String threadName;
        private String coupon;
        ThreadDemo( String name){
            threadName = name;
            System.out.println("Creating " +  threadName );
        }
        public void run() {
            WebDriver driver2 = new FirefoxDriver();
            //Operations on website
            coupon="Something";
    
        }
        public String getCoupon(){
            if (coupon==null){
                return "";
            }else{
                return coupon;
            }
        }
    
        public void start (){
            System.out.println("Starting " +  threadName );
            if (t == null){
                t = new Thread (this, threadName);
                t.start ();
            }
        }
    
    }
    

    Now just call it:

     ThreadDemo T1 = new ThreadDemo( "Coupon-code");
     T1.start();
     String coupon = "";
     while(coupon.equals("")) //<-This can be tweaked in 
                              //order to consume less memory and be faster
         coupon=T1.getCoupon();
    

    Tell me how it worked out!