Skip to content

Instantly share code, notes, and snippets.

@remarkablemark
Created June 28, 2016 19:18
Show Gist options
  • Save remarkablemark/39bfa535f4310474a907fda1a7e76784 to your computer and use it in GitHub Desktop.
Save remarkablemark/39bfa535f4310474a907fda1a7e76784 to your computer and use it in GitHub Desktop.
Get and set localStorage with WebDriverJS `executeScript` and `executeAsyncScript`.
'use strict';
/**
* Module dependencies.
*/
const webdriver = require('selenium-webdriver');
/**
* Build driver.
*/
const builder = new webdriver.Builder();
const driver = builder.forBrowser('phantomjs').build();
// make sure to open a page otherwise you will get the WebDriverError
// SecurityError: DOM Exception 18
driver.get('https://httpbin.org');
/**
* Set local storage item with `executeScript`.
*/
driver
.executeScript('return window.localStorage.setItem("key", "value");');
/**
* Get local storage item with `executeScript`.
*/
driver
.executeScript('return window.localStorage.getItem("key");')
.then((itemValue) => {
console.log(itemValue);
});
/**
* Set and get local storage item with `executeAsyncScript`.
*/
driver
.executeAsyncScript(function(callback) {
window.localStorage.setItem('foo', 'bar');
callback(window.localStorage.getItem('foo'));
})
.then((itemValue) => {
console.log(itemValue);
});
// close the driver
driver.quit();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment