I'm trying to get an item from local storage using Selenium Webdriver.
I followed this site but when I run my code I get NullPointerException
.
When I debug the code I see the function: getItemFromLocalStorage returns NULL for some reason.
Here is my code:
public class storage
{
public static WebDriver driver;
public static JavascriptExecutor js;
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver", "D://chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://html5demos.com/storage");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.id("local")).sendKeys("myLocal");
driver.findElement(By.id("session")).sendKeys("mySession");
driver.findElement(By.tagName("code")).click(); // just to escape textbox
String sItem = getItemFromLocalStorage("value");
System.out.println(sItem);
}
public static String getItemFromLocalStorage(String key)
{
return (String) js.executeScript(String.format(
"return window.localStorage.getItem('%s');", key));
}
}
That is because you forgot to instantiate js
object correctly. Add below line after driver = new ChromeDriver();
.
js = ((JavascriptExecutor)driver);
It will work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With