I need to save some items from local storage with c# (via js, because seems like there is no solution with 'pure' c#). I've tried this (sorry for code convention, I've been doing it in a hurry):
public string permissions;
public string expires;
public string token;
string storagePermissions = "localStorage.getItem('permissions')";
string storageExpires = "localStorage.getItem('expires')";
string storageToken = "localStorage.getItem('token')";
permissions = (string)js.ExecuteScript(storagePermissions);
expires = (string)js.ExecuteScript(storageExpires);
token = (string)js.ExecuteScript(storageToken);`
When I run this, it gets an empty string for these elements. My aim is to get local storage elements, save them to variables and use them with in another method:
string permissionsSetItemScript = "localStorage.setItem('permissions','{permissions}')";
string expiresSetItemScript = $"localStorage.setItem('expires','{expires}')";
string tokenSetItemScript = $"localStorage.setItem('token','{token}')";
js.ExecuteScript(permissionsSetItemScript);
js.ExecuteScript(expiresSetItemScript);
js.ExecuteScript(tokenSetItemScript);
CodePudding user response:
Try with this (Java example but C# should be pretty similar):
LocalStorage local = ((WebStorage) driver).getLocalStorage();
CodePudding user response:
Using javascript you can set an item or get an item from local storage
public static class WebDriverExtensions
{
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}')");
}
}
and then use these extension methods like:
driver.SetItemToLocalStorage("token", "your-token");
string token = driver.GetItemFromLocalStorage("token")