This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

Browser interactions

Get browser information

Get title

You can read the current page title from the browser:

Move Code

title = driver.title
            String title = driver.Title;
  it 'gets the current title' do
    let title = await driver.getTitle();
driver.title

Get current URL

You can read the current URL from the browser’s address bar using:

Move Code

url = driver.current_url
            String url = driver.Url;
  it 'gets the current url' do
    let currentUrl = await driver.getCurrentUrl();
driver.currentUrl

1 - Browser navigation

The first thing you will want to do after launching a browser is to open your website. This can be achieved in a single line:

        //Convenient
        driver.get("https://selenium.dev");
            
        //Longer way
        driver.navigate().to("https://selenium.dev");
driver.get("https://www.selenium.dev/selenium/web/index.html")
            //Convenient
            driver.Url = "https://selenium.dev";
            //Longer
            driver.Navigate().GoToUrl("https://selenium.dev");

  it 'navigates to a page' do
    driver.navigate.to 'https://www.selenium.dev/'
    //Convenient
      await driver.get('https://www.selenium.dev');
  
      //Longer way
      await driver.navigate().to("https://www.selenium.dev/selenium/web/index.html");
//Convenient
driver.get("https://selenium.dev")

//Longer way
driver.navigate().to("https://selenium.dev")
  

Back

Pressing the browser’s back button:

        //Back
        driver.navigate().back();
driver.back()
            //Back
             driver.Navigate().Back();
    driver.navigate.to 'https://www.selenium.dev/'
    //Back
      await driver.navigate().back();
driver.navigate().back() 

Forward

Pressing the browser’s forward button:

        //Forward
        driver.navigate().forward();
driver.forward()
            //Forward
             driver.Navigate().Forward();
    driver.navigate.to 'https://www.selenium.dev/selenium/web/inputs.html'
    //Forward
    await driver.navigate().forward();
driver.navigate().forward()

Refresh

Refresh the current page:

        //Refresh
        driver.navigate().refresh();
driver.refresh()
            //Refresh
             driver.Navigate().Refresh();
  it 'refreshes the page' do
    //Refresh
    await driver.navigate().refresh();
driver.navigate().refresh()

2 - JavaScript alerts, prompts and confirmations

WebDriver provides an API for working with the three types of native popup messages offered by JavaScript. These popups are styled by the browser and offer limited customisation.

Alerts

The simplest of these is referred to as an alert, which shows a custom message, and a single button which dismisses the alert, labelled in most browsers as OK. It can also be dismissed in most browsers by pressing the close button, but this will always do the same thing as the OK button. See an example alert.

WebDriver can get the text from the popup and accept or dismiss these alerts.


import static org.junit.jupiter.api.Assertions.assertEquals;

public class AlertsTest extends BaseTest {

    @BeforeEach
    element = driver.find_element(By.LINK_TEXT, "See an example alert")
    element.click()

    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    text = alert.text
    alert.accept()
//Click the link to activate the alert
driver.FindElement(By.LinkText("See an example alert")).Click();

//Wait for the alert to be displayed and store it in a variable
IAlert alert = wait.Until(ExpectedConditions.AlertIsPresent());

//Store the alert text in a variable
string text = alert.Text;

//Press the OK button
alert.Accept();
  
    # Store the alert reference in a variable
    alert = driver.switch_to.alert

    # Get the text of the alert
    alert.text

    # Press on Cancel button
    alert.dismiss
        let alert = await driver.switchTo().alert();
        let alertText = await alert.getText();
        await alert.accept();
//Click the link to activate the alert
driver.findElement(By.linkText("See an example alert")).click()

//Wait for the alert to be displayed and store it in a variable
val alert = wait.until(ExpectedConditions.alertIsPresent())

//Store the alert text in a variable
val text = alert.getText()

//Press the OK button
alert.accept()
  

Confirm

A confirm box is similar to an alert, except the user can also choose to cancel the message. See a sample confirm.

This example also shows a different approach to storing an alert:

        Assertions.assertEquals("Slow", alert.getText());

        alert.accept();

    }


    @Test
    element = driver.find_element(By.LINK_TEXT, "See a sample confirm")
    driver.execute_script("arguments[0].click();", element)

    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    text = alert.text
    alert.dismiss()
//Click the link to activate the alert
driver.FindElement(By.LinkText("See a sample confirm")).Click();

//Wait for the alert to be displayed
wait.Until(ExpectedConditions.AlertIsPresent());

//Store the alert in a variable
IAlert alert = driver.SwitchTo().Alert();

//Store the alert in a variable for reuse
string text = alert.Text;

//Press the Cancel button
alert.Dismiss();
  
    # Store the alert reference in a variable
    alert = driver.switch_to.alert

    # Get the text of the alert
    alert.text

    # Press on Cancel button
    alert.dismiss
        let alert = await driver.switchTo().alert();
        let alertText = await alert.getText();
        await alert.dismiss();
//Click the link to activate the alert
driver.findElement(By.linkText("See a sample confirm")).click()

//Wait for the alert to be displayed
wait.until(ExpectedConditions.alertIsPresent())

//Store the alert in a variable
val alert = driver.switchTo().alert()

//Store the alert in a variable for reuse
val text = alert.text

//Press the Cancel button
alert.dismiss()
  

Prompt

Prompts are similar to confirm boxes, except they also include a text input. Similar to working with form elements, you can use WebDriver’s send keys to fill in a response. This will completely replace the placeholder text. Pressing the cancel button will not submit any text. See a sample prompt.

        //Wait for the alert to be displayed and store it in a variable
        wait.until(ExpectedConditions.alertIsPresent());

        Alert alert = driver.switchTo().alert();
        Assertions.assertEquals("Enter something", alert.getText());
    element = driver.find_element(By.LINK_TEXT, "See a sample prompt")
    driver.execute_script("arguments[0].click();", element)

    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    alert.send_keys("Selenium")
    text = alert.text
    alert.accept()
//Click the link to activate the alert driver.FindElement(By.LinkText("See a sample prompt")).Click(); //Wait for the alert to be displayed and store it in a variable IAlert alert = wait.Until(ExpectedConditions.AlertIsPresent()); //Type your message alert.SendKeys("Selenium"); //Press the OK button alert.Accept();
    # Store the alert reference in a variable
    alert = driver.switch_to.alert

    # Type a message
    alert.send_keys('selenium')

    # Press on Ok button
    alert.accept
        let alert = await driver.switchTo().alert();
        //Type your message
        await alert.sendKeys(text);
        await alert.accept();
//Click the link to activate the alert driver.findElement(By.linkText("See a sample prompt")).click() //Wait for the alert to be displayed and store it in a variable val alert = wait.until(ExpectedConditions.alertIsPresent()) //Type your message alert.sendKeys("Selenium") //Press the OK button alert.accept()

3 - Working with cookies

A cookie is a small piece of data that is sent from a website and stored in your computer. Cookies are mostly used to recognise the user and load the stored information.

WebDriver API provides a way to interact with cookies with built-in methods:

It is used to add a cookie to the current browsing context. Add Cookie only accepts a set of defined serializable JSON object. Here is the link to the list of accepted JSON key values

First of all, you need to be on the domain that the cookie will be valid for. If you are trying to preset cookies before you start interacting with a site and your homepage is large / takes a while to load an alternative is to find a smaller page on the site (typically the 404 page is small, e.g. http://example.com/some404page)

Move Code


    WebDriver driver = new ChromeDriver();
    driver = webdriver.Chrome()
    driver.get("http://www.example.com")

    # Adds the cookie into current browser context
    driver.add_cookie({"name": "key", "value": "value"})
         driver.Url="https://www.selenium.dev/selenium/web/blank.html";
         // Add cookie into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("key", "value"));
    driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
    # Add cookie into current browser context
    driver.manage.add_cookie(name: 'key', value: 'value')
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');
import org.openqa.selenium.Cookie
import org.openqa.selenium.chrome.ChromeDriver

fun main() {
    val driver = ChromeDriver()
    try {
        driver.get("https://example.com")

        // Adds the cookie into current browser context
        driver.manage().addCookie(Cookie("key", "value"))
    } finally {
        driver.quit()
    }
}
  

It returns the serialized cookie data matching with the cookie name among all associated cookies.

Move Code

    }

    @Test
    public void addCookie() {
        driver.get("https://www.selenium.dev/selenium/web/blank.html");
    driver = webdriver.Chrome()
    driver.get("http://www.example.com")

    # Adds the cookie into current browser context
    driver.add_cookie({"name": "foo", "value": "bar"})

    # Get cookie details with named cookie 'foo'
    print(driver.get_cookie("foo"))
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         // Add cookie into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("foo", "bar"));
         // Get cookie details with named cookie 'foo'
         Cookie cookie = driver.Manage().Cookies.GetCookieNamed("foo");
    driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
    # Add cookie into current browser context
    driver.manage.add_cookie(name: 'foo', value: 'bar')
    # Get cookie details with named cookie 'foo'
    cookie = driver.manage.cookie_named('foo')
    // set a cookie on the current domain
    await driver.manage().addCookie({ name: 'foo', value: 'bar' });

    // Get cookie details with named cookie 'foo'
import org.openqa.selenium.Cookie
import org.openqa.selenium.chrome.ChromeDriver

fun main() {
    val driver = ChromeDriver()
    try {
        driver.get("https://example.com")
        driver.manage().addCookie(Cookie("foo", "bar"))

        // Get cookie details with named cookie 'foo'
        val cookie = driver.manage().getCookieNamed("foo")
        println(cookie)
    } finally {
        driver.quit()
    }
}  
  

Get All Cookies

It returns a ‘successful serialized cookie data’ for current browsing context. If browser is no longer available it returns error.

Move Code

        // Get cookie details with named cookie 'foo'
        Cookie cookie = driver.manage().getCookieNamed("foo");
        Assertions.assertEquals(cookie.getValue(), "bar");
    }


    @Test
    public void getAllCookies() {
        driver.get("https://www.selenium.dev/selenium/web/blank.html");
        // Add cookies into current browser context
        driver.manage().addCookie(new Cookie("test1", "cookie1"));
        driver.manage().addCookie(new Cookie("test2", "cookie2"));
        // Get cookies
        Set<Cookie> cookies = driver.manage().getCookies();
        for (Cookie cookie : cookies) {
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    driver.add_cookie({"name": "test1", "value": "cookie1"})
    driver.add_cookie({"name": "test2", "value": "cookie2"})

    # Get all available cookies
    print(driver.get_cookies())
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         // Add cookies into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("test1", "cookie1"));
         driver.Manage().Cookies.AddCookie(new Cookie("test2", "cookie2"));
         // Get cookies
         var cookies = driver.Manage().Cookies.AllCookies;
         foreach (var cookie in cookies){
             if (cookie.Name.Equals("test1")){
                 Assert.AreEqual("cookie1", cookie.Value);
             }
             if (cookie.Name.Equals("test2")){
                 Assert.AreEqual("cookie2", cookie.Value);
             }
         }
    driver.navigate.to 'https://www.selenium.dev/selenium/web/blank.html'
    # Add cookies into current browser context
    driver.manage.add_cookie(name: 'test1', value: 'cookie1')
    driver.manage.add_cookie(name: 'test2', value: 'cookie2')
    # Get cookies
    cookies = driver.manage.all_cookies
    await driver.manage().addCookie({ name: 'test2', value: 'cookie2' });

    // Get all Available cookies
import org.openqa.selenium.Cookie
import org.openqa.selenium.chrome.ChromeDriver

fun main() {
    val driver = ChromeDriver()
    try {
        driver.get("https://example.com")
        driver.manage().addCookie(Cookie("test1", "cookie1"))
        driver.manage().addCookie(Cookie("test2", "cookie2"))

        // Get All available cookies
        val cookies = driver.manage().cookies
        println(cookies)
    } finally {
        driver.quit()
    }
}  
  

It deletes the cookie data matching with the provided cookie name.

Move Code

        }
    }

    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    driver.add_cookie({"name"