Using LocalStorage within the Selenium Webdriver

Do LocalStorage stores differ between a regular browser and Selenium Browser? I've noticed that when I create an item on Selenium Chrome, it disappears after I close the browser. Is this supposed to happen? Additionally, I am unable to read the localStorage from a regular browser.

Edit: To clarify further:

If I enter the following in the console of my Selenium chrome browser

localStorage.setItem("test", "This is a test value"); 
localStorage.getItem("test");
=> correctly prints "This is a test value"

However, if I close the Selenium chrome browser, reopen it, and try to retrieve the same value on the same page with localStorage.getItem("test"); => returns null

Despite reading various posts about being able to use localStorage in Selenium, I'm facing this issue.

Answer №1

JavaScript / Node

I encountered a similar issue as discussed in previous responses; the local storage is specific to each profile, and Selenium creates a new profile with an empty local storage every time it launches.

To maintain the local storage between multiple Selenium page launches, you can utilize the same profile:

const webdriver = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');

const chromeProfilePath = 'C:\\Users\\Bob\\AppData\\Local\\Google\\Chrome\\User Data';

let options = new chrome.Options();
options.addArguments(`--user-data-dir=${chromeProfilePath}`); 
let driver = new webdriver.Builder()
    .forBrowser('chrome')
    .setChromeOptions(options)
    .build();

You can find the profile path by entering chrome://version in your browser.

IMPORTANT: make sure to remove the "default" from the end of the path as Chrome automatically appends it back.

Additionally, any changes in Chrome/ChromeDriver post version 74 may impact how options are applied in selenium-webdriver - ensure compatibility with the appropriate version of selenium-webdriver.

Answer №2

It's important to note that localStorage is persistent across browser re-openings, unlike sessionStorage, which does not survive even a tab close. However, this persistence is specific to each browser profile.

When Chrome and Firefox sessions are created, they start with a fresh profile by default. This explains why your localStorage data was erased.

In the example provided, the entries made in the first session were saved, but once a new session started in a different profile, the localStorage appeared empty.

This default behavior of starting with a new profile makes sense because sharing or preserving localStorage between browser reopenings could lead to contamination from previous sessions, resulting in unexpected outcomes.

To override this default behavior, browsers can be launched with specific profiles for persistence if required.

While Chrome and Firefox begin with a new profile, Internet Explorer starts with a default one, potentially retaining localStorage. However, this is subject to confirmation :)


Contrary to common belief, localStorage is stored on the user's disk drive, ensuring its persistence, rather than in the browser's memory. In contrast, sessionStorage exists solely in memory, guaranteeing that it will not endure browser reopenings.

Answer №3

When it comes to where data is stored, the answer lies within the browser itself, not Selenium. Once you close the final tab or window, the data vanishes into thin air.

If you utilize localStorage.setItem in a browser and then open another tab or window in the same session, the data remains accessible. However, once that last tab or window is closed, say goodbye to your precious information.

In essence, to ensure continuity of data usage across browser windows, make sure to manage it before shutting down that final window or tab.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ajax is unintentionally duplicating the request

When the "async" parameter is set to "true", ajax sends two requests at the same time. But, when it is set to "false", there are no issues. To prevent the page from reloading, I am using the following code: $(document).ready(function() { $(document).on(& ...

Using JQuery to load elements and applying Select2 functionality

I'm currently utilizing select2 in a project, and it's functioning properly by initializing the select2 using: $(function() { $(".elegible").select2(); }); The problem arises when I attempt to apply the function to elements loaded through jQ ...

Bus Boy's employment record shows no termination

I am working on a Next Js project that includes an upload image endpoint. const busboy = require('busboy') export default function handle(req, res) { const bb = busboy({headers: req.headers}); bb.on('file', (fieldname, file, fi ...

Explore all attributes of a specific tag in BeautifulSoup to locate a particular word

As I was working on a web scraping project to extract prices from a specific website, I encountered a coding challenge. Here is the code snippet I used: price = soup.findAll(['div'],{'class':re.compile(r'(.*?price.*?)',re.IGN ...

The dynamic sidebar menu in Adminlte 3 with bootstrap-4 loaded from ajax is not functioning properly, presenting issues with sidebar

Is there a way to fetch dynamic sidebar menu data from the database using AJAX in the adminlte 3 dashboard along with bootstrap 4? I have tried loading the sidebar menu data dynamically using AJAX, but the sidebar open/close functionality is not working pr ...

Can jQuery and Google Analytics be loaded together in a single process?

My current setup includes the following: <script src="http://www.google.com/jsapi?key=..." type="text/javascript"></script> <script> //<![CDATA[ google.load('jquery', '1.6'); //]]> </script> &l ...

Ways to retrieve base64 encoded information from an image within an HTML document

On my registration form, users have the option to select an avatar from 2 choices: Select a default avatar Upload their own custom avatar This is how I have implemented it in my HTML page. <img id="preview" src="img/default_1.png"> The chosen av ...

How can you make nested JSON values optional in Joi Validation?

As I work on my API, I encounter a nested JSON structure that serves as the payload for the endpoint. Here is an example of what it looks like: {"item_id":"1245", "item_name":"asdffd", "item_Code":"1244", "attributes":[{"id":"it1","value":"1"},{"id":"it2" ...

Navigating through various div elements in Javascript and sending parameters to a script

Context In my project, I am using PHP to generate a series of voting sections. Each section follows the same format except for a unique number assigned to it, which increases with each iteration of the PHP loop. To keep track of the unique numbers, I uti ...

Mapping the Way: Innovative Controls for Navigation

Currently, I am utilizing the HERE maps API for JavaScript. However, I would like to customize the design of the map controls similar to this: Below is an example for reference: HERE EXAMPLE Is it feasible to achieve this customization? ...

retrieving the selected date from the calendar widget

I'm utilizing jQuery's datepicker to collect date inputs from users. The form is structured as below: <form id="myform" action="/graphs/get_builds" method="post"> Start: <input type="text" id="start" /> End: <input type="t ...

What measures can I take to ensure a function is only executed once, even in cases where multiple change events are triggered simultaneously?

Individual checkbox clicks work smoothly without any issues. However, checking all checkboxes at once may cause problems when dealing with a large number of municipalities to loop through, leading to flickering in the dropdown and preventing users from sel ...

Utilizing Angular partials within specific views with the assistance of ui-router

I am currently working on developing a MEAN application and facing some challenges while handling ui-router. Within my index.html file, I have set up the template for the entire website including a header, sidebar, and content area where I have placed < ...

How to Fetch a Singular Value from a Service in Angular 4 Using a Defined Pattern

I am currently working on developing a service in Angular 4 (supported by a C# RESTful API) that will facilitate the storage and retrieval of web-application wide settings. Essentially, it's like a system for key-value pair lookups for all common appl ...

Error: The object 'require' is not recognized in Vue Component

I am facing an issue while using screenfull.js (import screenfull from "screenfull") in a Vue component. Can anyone help me with this problem? Here is the error information. Version: Vue: 2.6.14 @vue/cli-service: 5.0.4 Babel-loader: 8.2.5 Vue-loader: ...

Is it possible for Selenium to not be able to click a button using Python?

Could really use some assistance with this! I'm having trouble getting selenium to click a button using python. I'm currently working on Python 3.4 and using Firefox 42. The browser opens, but that's as far as it goes. from selenium impor ...

What is the best way to display pages with different states in ExpressJS?

Here is a code block that I have: var express = require('express'); var newsRouter = express.Router(); newsRouter.get('/:news_param', (req, res) => { let news_params = '/haberler/' + req.params.news_param; req.ne ...

Utilize Regular Expressions to validate phone numbers

Currently tackling a Regex challenge. let phones = ['321-1234567','+355 321 1234567','0103 1234500', '00 355 3211234567' ] Desired results: 3211234567 +3553211234567 +3551031234500 +3553211234567 Implemented soluti ...

How come setting setTimeout to zero did not cause the code to enter an endless recursive loop?

I found this snippet of code on a website that discusses async callback functions and the event loop in JavaScript. I am curious as to why the line timer = setTimeout(arguments.callee, 0) does not create a recursive loop since it is being executed withou ...

Discovering an <a> element with an href attribute containing two specified strings

Here's what I have: $("a[href*='string1' && 'string2']") Unfortunately, this code didn't work for me. I also attempted: $("a:contains('string1' && 'string2')") The second one only return ...