How to set localstorage in selenium + node js?

Viewed 1801

I am trying to set local storage using nodeJs + selenium. Actually I tried with Java + Selenium with the below code it works well for me.

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("localStorage.setItem(arguments[0],arguments[1])", "Id", "{\"_expired\":0,\"_value\":\"133\"}")

But, unable to achieve the same thing using nodeJs, Already tried some methods like-

localStorage.setItem('Id', '{\"_expired\":0,\"_value\":\"133\"}');

but Instead of putting in browser local storage, it is writing on some local files.

LocalStorage

I want to set key and value in Application >> Local Storage >>{site url}

3 Answers

Please try the below snippet. Hope it will work!

driver.executeScript(function () {
    localStorage.setItem("Id", '{\"_expired\":0,\"_value\":\"133\"}');
});

You can't access browser's localstorage from node JS.

You can use this package Store for your job though,

const store = require('store');
store.set('myObj', { name:'foo' })
 
// Get myObj
store.get('myObj')

You can also use this:

driver.executeScript(
        "localStorage.setItem(arguments[0], arguments[1])", key, value
    );
Related