Ways to store session storage item in a variable

I am looking for a way to save items from local storage using C# (via JS, as there doesn't seem to be a solution with pure C#). I quickly tried the following code:


public string token;

string storageToken = "localStorage.getItem('token')";

token = (string)js.ExecuteScript(storageToken);`

However, when I run this code, it returns an empty string for these elements. My goal is to retrieve local storage elements, store them in variables, and then use them in another method:


string tokenSetItemScript = $"localStorage.setItem('token','{token}')";

js.ExecuteScript(tokenSetItemScript);

Answer №1

If you're looking for a solution, consider the following code snippet (this is in Java but C# syntax should be quite similar):

LocalStorage storage = ((WebStorage) driver).getLocalStorage();

Answer №2

One handy feature of javascript is the ability to interact with local storage items - setting and retrieving them.

public static class LocalStorageManager
{
    public static void SetItemToLocalStorage(this IWebDriver driver, string key, string value)
    {
        var js = (IJavaScriptExecutor)driver;
        js.ExecuteScript("localStorage.setItem(arguments[0],arguments[1])", key, value);
    }

    public static string GetItemFromLocalStorage(this IWebDriver driver, string key)
    {
        var js = (IJavaScriptExecutor)driver;
        return (string)js.ExecuteScript($"return window.localStorage.getItem('{key}')");
    }
}

You can then use these extension methods like so:

driver.SetItemToLocalStorage("token", "your-token");
string token = driver.GetItemFromLocalStorage("token")

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

Secure access to an API using a certificate within a Vue.js application running on localhost

My vue.js app is built using vue-cli. The application is hosted at dev.example.com and the REST API can be found at dev.example.com/api/v1/. The backend has added an SSL certificate for security on the development environment. However, when I try to make a ...

What is preventing me from accessing the sub-elements of an AngularJS controller?

I know this question has probably been asked countless times before, but I'm struggling to find the right words to explain my specific issue. Essentially, I'm having trouble accessing something like $ctrl.thing.subelement. However, the following ...

What is the best way to retrieve the Axios Post response in React?

I'm facing a small issue. In my ReactJS code, I have a post function that is functioning correctly. However, I want to access the response of this function outside its scope, right where I called it. Is there a way to achieve this? async function che ...

Adding an object to an array of objects with the useState hook in React - A simple guide

Hello, I am currently working on a project that involves creating a dynamic test page with questions, answers, and points/grades. The goal is to generate input fields based on the number of questions selected by the admin, along with an "Add Question" butt ...

Sending a base64 image of a canvas to a servlet

I have a JavaScript function that uploads HTML5 canvas base64 image data to a servlet. Here is the code: function saveDataURL(a) { var postData = "canvasData="+a; var ajax = new XMLHttpRequest(); ajax.open("POST",'uploadPhoto.cgi',tr ...

Summing Values with Linq.js Filter

Can you apply a filter in Linq.JS using SUM? This is my attempt: var query = Enumerable .From(self.data()) .Where("$$.Sum($.percent) > 100") .ToArray(); Issue encountered: linq.js: Uncaught TypeError: $$.Sum is ...

Detach attention from TextField select component in Material UI and React through manual means

When I create a select input using the TextField component from Material-UI library, I need to manually remove focus after an option is selected. I attempted to achieve this by using a reference to the TextField with the 'inputRef' prop. However, ...

Using the HTTP DELETE method in Node.js

Is there a specific configuration required before sending DELETE requests to a node.js application? I am able to send GET, POST, and PUT requests successfully, but for some reason DELETE requests are not functioning. When I try DELETE http://localhost:80 ...

Troubleshooting a visual problem using react-easy-crop within a React MUI Dialog

I'm having trouble adjusting the layout of MUI Dialog in combination with react-easy-crop. My goal is to achieve a perfect display of the dialog using react-easy-crop. However, the react-easy-crop component is covering the entire dialog. I attempted t ...

Utilizing the Singleton Pattern to Prevent Null Values in Asp.Net Sessions

I need the "GetClassTeacher" method in my Asp.net application to be executed only once per session. To achieve this, I am currently using a session check to ensure that the object is null before calling the database. My query is whether this approach is t ...

jQuery tipsy not triggering click event in Internet Explorer

Hey there! I've been using the jquery tipsy plugin for displaying colour names above colour swatch images. One thing I'm trying to do is trigger a checkbox to be checked/unchecked when a user clicks on the image. $(document).ready(function(){ ...

The Upload Button on AjaxFileUpload Failed

I have been diligently searching for a solution to my issue and have tried numerous options, but have not come across anyone with a similar problem. The code I have inserted into my page seems to be working fine. I have tried using both the regular Toolki ...

Best Practices for Implementing AngularJS Dependency Injection

I am excited to share that I have recently started delving into my very first Angular JS project. As I navigate through this new experience, I want to ensure that I am effectively managing Multiple dependency injection. Any insights, recommendations, or ...

What are the steps to resolve the error 'content-type missing boundary' and encountering the issue with getBoundary not being recognized as a function?

fetchCarouselData: async (params) => { let bodyFormData = new FormData(); for (let prop in params) { bodyFormData.append(prop, params[prop]); } return axios({ method: "post", url: `${baseURL}/fetchCarouselData`, data: b ...

How can you leverage Symfony to iterate through a JSON array efficiently?

After selecting a user, I am attempting to display a list of contracts. To achieve this, I have written the following query: /** * @param $firstname * @param $lastname * @return mixed * @throws DBALException */ public function getListPerUser($firs ...

Add an event listener to a specific class in order to control the visibility of its child elements by

Whenever I click on the "title text" link, the <ol> element refuses to hide, despite my efforts. After thoroughly reviewing the jQuery documentation and scouring Stack Overflow for answers related to .click(), .children(), .toggle(), and .hide(), I a ...

Execute a JavaScript code prior to sending a response directly from the ASP.NET code behind

On my .aspx page, I have the following code which prevents the page from responding without confirmation: <script type="text/javascript"> window.onbeforeunload = confirmExit; function confirmExit() { return 'Are you sure you wan ...

Sending parameters from one Node.js function to another in separate JavaScript files

I am currently working on passing function responses between two Node.js scripts. Here is my approach. Index.js var express = require('express'); require('./meter'); var app = express(); app.get('/',function(req,res){ ...

Identifying a specific field in a dynamically generated React.js component: Best practices

Currently, I am in the process of developing a form with an undetermined number of sensor fields. The front end has been successfully implemented and now my focus is on extracting user information from these dynamically generated component fields. Here is ...

Tips for keeping the hover effect of a sibling element in Material-UI

Card Component import image from "../../Assets/pic.jpg"; import React, { useState } from "react"; import { makeStyles } from "@material-ui/core/styles"; import Card from "@material-ui/core/Card"; import CardActionAre ...