Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webdriver get Item From Local Storage

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));
    }
}
like image 752
John Avatar asked Nov 01 '22 06:11

John


1 Answers

That is because you forgot to instantiate js object correctly. Add below line after driver = new ChromeDriver();.

js = ((JavascriptExecutor)driver);

It will work.

like image 116
Priyanshu Shekhar Avatar answered Nov 15 '22 05:11

Priyanshu Shekhar