Skip to main content

Command Palette

Search for a command to run...

Access Browser Local Storage Using Selenium

Updated
4 min read

In the domain of web development and automation testing, managing browser local storage efficiently is crucial. Whether you're a developer implementing local storage features or a QA engineer ensuring the functionality of a web application, having the ability to manipulate local storage through automated tests can significantly streamline the testing process. In this blog, we'll explore how to manage browser local storage using Selenium, a popular automation tool for web browsers.;

Understanding Browser Local Storage:

Before diving into Selenium automation, let's grasp the concept of browser local storage. Local storage is a key-value storage mechanism provided by web browsers to store data persistently across browser sessions. This data remains available even after the browser is closed and reopened. It's commonly used by web applications to store user preferences, session data, or any other relevant information.

Why Manage Local Storage with Selenium?

Selenium is widely used for automating web browsers to perform tasks such as testing web applications, scraping web content, or automating repetitive tasks. When it comes to testing web applications, the ability to manipulate browser local storage through Selenium scripts becomes invaluable. By controlling the local storage, testers can simulate various scenarios and ensure that the application behaves as expected under different data conditions.

Benefits of Local Storage Management with Selenium: Efficient local storage management using Selenium offers several benefits:

  • Improved Test Coverage: By manipulating local storage, testers can simulate various user scenarios, enhancing test coverage.

  • State Management: Testers can control the application's state by setting and clearing local storage items, ensuring consistent test environments.

  • Data Preloading: Preloading data into local storage facilitates testing of specific application functionalities without relying on external data sources.

  • Validation of Data Persistence: Verifying the persistence of data stored in local storage validates the application's behavior under different conditions.

Managing Local Storage with Selenium

Setup:

Before we begin, make sure you have Selenium WebDriver set up in your preferred programming language (e.g., Python, Java, JavaScript). You can install Selenium via package managers like pip (for Python) or npm (for JavaScript).

Steps:

  1. Launch Browser:

Start by launching the browser using Selenium WebDriver. You can choose the browser of your preference (e.g., Chrome, Firefox).

  1. Navigate to the Target URL:

Load the web page of the application you want to test by navigating to its URL using Selenium WebDriver's get() method.

  1. Access Local Storage:

Selenium provides a couple of ways to access browser local storage:

  • By using LocalStorage interface.

  • By using JavaScript Executor

  1. Add/Update Key-value in Browser Local Storage:

// Using JavaScript Executor 
JavascriptExecutor jexecutor = (JavascriptExecutor) remdriver; 
jexecutor.executeScript("window.localStorage.setItem('key', 'value')");

// Using LocalStorage Interface 
RemoteExecuteMethod executeMethod = new RemoteExecuteMethod((RemoteWebDriver) remdriver); 
RemoteWebStorage webStorage = new RemoteWebStorage(executeMethod); 
LocalStorage storage = webStorage.getLocalStorage(); 
storage.setItem(key, value);

This line of code sets a key-value pair in the local storage.

  1. Retrieve Local Storage Data:

    Similarly, you can retrieve data from local storage:

// Using JavaScript Executor 
JavascriptExecutor jexecutor = (JavascriptExecutor) remdriver; 
jexecutor.executeScript("window.localStorage.getItem('key')");

// Using LocalStorage Interface 
RemoteExecuteMethod executeMethod = new RemoteExecuteMethod((RemoteWebDriver) remdriver); 
RemoteWebStorage webStorage = new RemoteWebStorage(executeMethod); 
LocalStorage storage = webStorage.getLocalStorage(); 
storage.getItem(key);

This code retrieves the value associated with the specified key from local storage.

Bonus:

Here is the cucumber BDD implementation of the Local Storage interface using Selenium/Java.

Feature File:

@regression  
Scenario: validate Local Storage interface  
  And "the user" add the following value in local storage  
    | Key         | value |  
    | userConsent | True  |  
  And "the user" validate the following value in local storage  
    | Key         | expected value |  
    | userConsent | True           |  
  And "the user" delete the following value in local storage  
    | Key         |  
    | userConsent |

StepDef:

@And("^\"([^\"]*)\" (add|delete|validate) the following value in local storage$")  
public void localStorage(String strArg1,  
                        String type,  
                        DataTable attributesTable) throws Throwable {  
    if ("app".equalsIgnoreCase(Constants.browserOrApp)) {  
        throw new StepDefNotApplicableForMobileException("Not Applicable On Mobile App");  
    }  
    elements = Utils.sanitizeDatatable(attributesTable.asLists());  
    RemoteExecuteMethod executeMethod = new RemoteExecuteMethod((RemoteWebDriver) remdriver);  
    RemoteWebStorage webStorage = new RemoteWebStorage(executeMethod);  
    LocalStorage storage = webStorage.getLocalStorage();

    for (int i = 1; i < elements.size(); i++) {  
        String key = elements.get(i).get(0);  
        if (type.equalsIgnoreCase("add")) {  
            String value = elements.get(i).get(1);  
            storage.setItem(key, value);  
        } else if (type.equalsIgnoreCase("delete")) {  
            storage.removeItem(key);  
        } else if (type.equalsIgnoreCase("validate")) {  
            String valuetovalidate = elements.get(i).get(1);  
            Assert.assertEquals(valuetovalidate, storage.getItem(key).toString());  
            logger.info(valuetovalidate + ": Key is present in local storage");  
        }  
    }  
}
A

👍