How to refresh browser in Selenium WebDriver using different methods

In this article, we will talk about how can we refresh browser using various methods.

Some time it is required to refresh the webpage to accomplish the testing objective. Let us see how this can be achieved.

Method1: Using navigate().refresh() method

Method2: Using JavaScriptExecutor

Method3: Using Actions Class

Mehtod4: Get the current URL & navigate using get() method

Method5: Get the current URL & navigate using navigate().to() method

Look at the below example –
package basicsOfSelenium;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class RefreshBrowserInDiffWays {

 public static void main(String[] args) {

  WebDriver driver = new FirefoxDriver();
  driver.navigate().to("https://www.google.co.in");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  // Method1:  Using navigate().refresh() method
  driver.navigate().refresh();
  
  //Method2: Using JavaScriptExecutor
  JavascriptExecutor js = (JavascriptExecutor)driver;
  js.executeScript("history.go(0)");
  
  //Method3: Using Actions Class
  Actions actions = new Actions(driver);
  actions.keyDown(Keys.CONTROL).sendKeys(Keys.F5).perform();
  
  //Mehtod4: Get the current URL & navigate using get() method
  driver.get(driver.getCurrentUrl());
  
  //Method5: Get the current URL & navigate using navigate().to() method
  driver.navigate().to(driver.getCurrentUrl());
  
 }

}

Hope this helps!!!!

How to handle Authentication Required popup using AutoIT?

While browsing some websites, Authentication required popup comes asking username and password. Observe below snap.

Now, this can be handled using either robot class or by using AutoIT script.
Let us see how this Authentication Required popup is handled using AutoIT script.
Script used to handle this Authentication popup is as below –
WinWaitActive(“Authentication Required”,””,”10″)

 

If WinExists(“Authentication Required”) Then

 

Send(“username{TAB}”)

 

Send(“Password{Enter}”)

 

EndIf
Add this script in SciTE editor. Save the file with some name by .au3 extension.
Now compile the script by right clicking on it, with respective version.
Once compilation is successful, .exe file will be created with same name.
Now, we can use this .exe file & run this via our selenium Webdriver script.
                        Runtime.getRuntime().exec(“C:/Users/Prakash/Desktop/TestScript.exe”);
That’s, all, this is how we can handle Authentication Required Popup using AutoIT

How to upload file in Selenium WebDriver using Robot class

Upload file using Robot class –

Suggested post to read –  How to upload file in Selenium WebDriver using sendKeys() method

In this article, we will see how can we upload file in Selenium WebDriver using robot class.

Upload file in Selenium WebDriver using ROBOT Class

This is another way using which we can upload file. Here we can do key press and key release using robot class.

This method is for handling the Windows File Upload dialog, which cannot be handled using Selenium. Please follow below steps:

1.   Click on the File Upload / Choose File button, so that the File Upload dialog is displayed.
        driver.findElement(By.xpath(“//*[@id=’uploadfile_0′]”)).click();

2. Copy your file’s absolute path to the clipboard
    StringSelection ss = new StringSelection(” C:UsersPrakashDesktopDesktopTOSCA tutorial.pptx”);
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);

3. Paste the file’s absolute path into the File name field of the File Upload dialog box

    //native key strokes for CTRL, V and ENTER keys

    Robot robot = new Robot();
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);

Refer below code –

package basicsOfSelenium;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


public class FileUploadInSelenium_UsingRobotClass {

 public static void main(String[] args) throws AWTException {

  WebDriver driver = new FirefoxDriver();
  driver.navigate().to("http://demo.guru99.com/selenium/upload/");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  //open upload window
     driver.findElement(By.xpath("//*[@id='uploadfile_0']")).click();

     //put path to your image in a clipboard
     StringSelection ss = new StringSelection("C://Users//Prakash//Desktop//Desktop//TOSCA tutorial.pptx");
     Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);

     //imitate mouse events like ENTER, CTRL+C, CTRL+V
     Robot robot = new Robot();
     robot.delay(250);
     robot.keyPress(KeyEvent.VK_ENTER);
     robot.keyRelease(KeyEvent.VK_ENTER);
     robot.keyPress(KeyEvent.VK_CONTROL);
     robot.keyPress(KeyEvent.VK_V);
     robot.keyRelease(KeyEvent.VK_V);
     robot.keyRelease(KeyEvent.VK_CONTROL);
     robot.keyPress(KeyEvent.VK_ENTER);
     robot.delay(90);
     robot.keyRelease(KeyEvent.VK_ENTER);

  
 }

}

Refer below articles to learn more about Actions class in Selenium WebDriver –

Hope this helps !!

Handle datePicker in selenium using JavaScript

In this article, will talk about how to Handle datePicker in selenium using JavaScript.
Suggested post to read:
In old applications, the datepicker was in old style, that is, it was a kind of dropdowns, by using select class. But in new applications now, Datepicker are not Select element.
Datepicker are in fact table with set of rows and columns. To select a date, you just have to navigate to the cell where our desired date is present. Look at the below snapshot.
So, to handle this datePicker, we will write a java script, in which firstly we will enable the datebox (which is restricted by default to enter the value manually rather than selecting it from calendar pop-up). Then We will clear that filed & then enter the date by using sendKeys() method.
Look at the below example –
package basicsOfSelenium;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class HandleDatePcikerUsingJavaScript {

 public static void main(String[] args) {

  WebDriver driver = new FirefoxDriver();
  driver.navigate().to("https://www.redbus.in/");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  //This will select From date 
  WebElement elementFromDate = driver.findElement(By.id("onward_cal"));
  ((JavascriptExecutor)driver).executeScript ("document.getElementById('onward_cal').removeAttribute('readonly',0);"); // Enables the from date box
  elementFromDate.clear();
  elementFromDate.sendKeys("18-Aug-2017"); //Enter date in required format
  
  
 }

}

Hope this helps !!

How to use JavaScriptExecutor in selenium WebDriver?

In this article i will talk about how to use JavaScriptExecutor in Selenium WebDriver.

Suggested post to read:

 What is JavaScriptExecutor in selenium WebDriver?

Let us understand first what is JavaScriptExecutr. It is an interface which is used to execute JavaScript in selenium Webdriver code.

Selenium WebDriver uses pre-defined locators like id, class, Xpath, name, link etc. to locate the elements on webpage. So, in some cases, it becomes difficult to locate element or sometimes you may face consistency problem in locating element due to webpage code.

Many Situations occur in your project where code written with selenium – java (any language binding) does not work (at all or effectively).

There would be few tricky scenarios where just Webdriver object is not sufficient enough or optimum enough to handle with java for e.g. in few of my applications, the web page rendered is very long, and while doing operations with elements, I got errors. So, I used JavaScript in my script to handle the case. Some other cases where JavaScript comes handy is handling pop ups and alerts.

In another case, dropdown wasn’t working for me (it was not properly coded by using select class). It was selecting the elements with are currently visible, wasn’t searching in to the whole list. So, in this case, I need to keep scrolling down continuously & at the same time keep checking If the required option is available to select & is getting selected.

So, there are certain advantages involved when we use the two (java, JavaScript) judiciously in automation scripts. Both the languages are great in their own space.

What are the advantages of JavaScriptExecutr in Selenium?

1.      JavaScript is very efficient & accurate, as compare to the scripts written with Selenium-Java
2.     JavaScript executor allows you to run pure JavaScript code irrespective of the Selenium language binding (Java, C#, Python etc.) you are using.
3.     By using JavaScript, you can directly interact and /or alter elements on the page, more or less, like the page developer has done.
4.     JavaScript being a language which works very well with HTML offers innumerous workarounds/hacks on the page.
5.     JavaScript is recommended to use when Selenium – Java code tends to break for certain scenario, where JavaScript works perfectly.
6.     JavaScript is quite easy to pick up with the least amount of setup required. No special setup is required while using it with selenium
How to use JavaScriptExecutr (JavaScriptExecutr Syntax) –
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(Script,Arguments);
Where –
script – The JavaScript to execute
Arguments – The arguments to the script. (Optional)
Let us see few of the uses where we can use javaScripts in selenium WebDriver code.
       1.       To refresh browser
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“history.go(0)”);
       2.       To get Webpage title
JavascriptExecutor js = (JavascriptExecutor)driver;
String sText =  js.executeScript(“return document.title;”).toString();
        3.       To click on the button
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", element);
      where, element is the button webElement where you wanted to click.
         4.       To Scroll down the webpage
  JavascriptExecutor js = (JavascriptExecutor)driver;
  js.executeScript("window.scrollBy(0,50)");
-> This is to scroll 50 pixels down.
If you want to scroll down till the end of webpage, then –
  js.executeScript("window.scrollBy(0,document.body.scrollHeight)");
        5.       To navigate to webpage –
JavascriptExecutr js = (JavascriptExecutr)driver;
js.executeScript("window.location = ‘URL-TO-BE-NAVIGATED’");

          6.       To enter text in textbox using JavaScript
           JavascriptExecutr js = (JavascriptExecutr)driver; 
           js.executeScript(“document.getElementById(‘lst-ib’).value = ‘Text to be searched’;”);
Example of JavaScriptExecutor –
package basicsOfSelenium;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class JavaScriptExample {

 public static void main(String[] args) {
  
  WebDriver driver = new FirefoxDriver();

  //Navigate to google.com using javascript
  JavascriptExecutor js = (JavascriptExecutor)driver;
  js.executeScript("window.location = 'https://www.google.co.in'");
 
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  //Enter the text in textbox using javascript
  js.executeScript("document.getElementById('lst-ib').value = 'Text to be searched';");
  
  //Click on the button using javascript
  WebElement element  = driver.findElement(By.xpath("//*[@id='tsf']/div[2]/div[3]/center/input[1]"));
  js.executeScript("arguments[0].click();", element);

  //Get page Title using JavaScript
  String PageTitle =  js.executeScript("return document.title;").toString();
  System.out.println("Page title is: "+PageTitle);
  
  //To Refresh the browser using JavaScript
  js.executeScript("history.go(0)");
  
  //To Scroll Down the webpage 
    js.executeScript("window.scrollBy(0,50)");
    
    //to Scroll the webpage to bottom of page
    js.executeScript("window.scrollBy(0,document.body.scrollHeight)");
 }

}

Hope this example helps little bit to understand how to use JavaScript in selenium – java code.