Similar to local storage, session storage stores the data for only one session. The data is deleted when the user closes the browser window. We can access the session storage using the sessionStorage
interface through JavaScript.
In this recipe, we will verify that a web page stores data in session storage as expected.
Let's create a test case that will load a web page that implements a counter and stores the value of the counter every time a button is clicked in session storage. We will verify that a new counter value is stored in session storage:
package com.secookbook.examples.chapter10; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebElement; import org.openqa.selenium.By; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class HTML5SessionStorage { private WebDriver driver; @Before public void setUp() { System.setProperty("webdriver.chrome.driver", "src/test/resources/drivers/chromedriver.exe"); driver = new ChromeDriver(); driver.get("http://cookbook.seleniumacademy.com/html5storage.html"); } @Test public void testHTML5SessionStorage() throws Exception { WebElement clickButton = driver.findElement(By.id("click")); WebElement clicksField = driver.findElement(By.id("clicks")); JavascriptExecutor jsExecutor = (JavascriptExecutor) driver; // Get current value of sessionStorage.clickcount, should be null String clickCount = (String) jsExecutor .executeScript("return sessionStorage.clickcount;"); assertEquals(null, clickCount); assertEquals("0", clicksField.getAttribute("value")); // Click the Button, this will increase the sessionStorage.clickcount // value by 1 clickButton.click(); // Get current value of sessionStorage.clickcount, should be 1 clickCount = (String) jsExecutor .executeScript("return sessionStorage.clickcount;"); assertEquals("1", clickCount); assertEquals("1", clicksField.getAttribute("value")); } @After public void tearDown() { driver.quit(); } }
While executing this test, whenever a button is clicked by Selenium WebDriver, a new session storage key is created for the first time in session storage. For subsequent clicks, this value is incremented by the web page.
Similar to local storage, we can validate this by accessing the clickCount
key from the sessionStorage
interface using the executeScript()
method of the JavaScriptExecutor
class. This will return the value of the clickCount
key as a String
:
//Click the Button, this will increase the sessionStorage.clickcount //value by 1 clickButton.click(); //Get current value of sessionStorage.clickcount, should be 1 clickCount = (String) jsExecutor.executeScript("return sessionStorage.clickCount;");
When the browser is closed and the test has ended, the clickcount
key will be removed from session storage.
18.118.27.119