Webdriver get Item From Local Storage - java

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.

I assume you have NPE on your driver instance.
You can setup driver location property while driver instance creating:
final ChromeDriverService chromeDriverService = new ChromeDriverService.Builder()
.usingDriverExecutable(new File("D://chromedriver.exe")).build();
driver = new ChromeDriver(chromeDriverService);
BTW, I used selenium 2.44.0

Use this Code
WebStorage webStorage = (WebStorage) new Augmenter().augment(driver);
LocalStorage localStorage = webStorage.getLocalStorage();
String user_data_remember = localStorage.getItem("user_data_remember");
String emailAfterLogout;
String passwordAfterLogout;
if (!user_data_remember.equals("")) {
JSONObject jsonObject = new JSONObject(user_data_remember);
Boolean remember = jsonObject.getBoolean("remember");
if (remember) {
emailAfterLogout = jsonObject.getString("email");
passwordAfterLogout = jsonObject.getString("password");
if (emailAfterLogout.equals(email) && passwordAfterLogout.equals(password)) {
System.out.println("Remember me is working properly.");
} else {
System.out.println("Remember me is not working.");
}
}
} else {
System.out.println("Remember me checkbox is not clicked.");
}

Related

while using id and xpath i am getting error but while using name i am not getting error

public class First {
public static String browser = "chrome";
public static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
if (browser.equals("firefox")) {
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
}
if (browser.equals("chrome")) {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
}
driver.get("https://www.salesforce.com/in/");
driver.findElement(
By.xpath("//*[#id=\"main\"]/div[2]/div/div/div/div[2]/div[1]/div[1]/div[3]/div/div[1]/div/a")).click();
Set<String> windowHandles = driver.getWindowHandles();
Iterator<String> windowIterator = windowHandles.iterator();
String parentWindow = windowIterator.next();
String childWindow = windowIterator.next();
System.out.println(driver.getTitle());
driver.switchTo().window(childWindow);
System.out.println(driver.getTitle());
driver.findElement(By.id("UserFirstName-m8NQ")).sendKeys("sam");
driver.findElement(By.xpath("//*[#id='UserFirstName-m8NQ']")).sendKeys("sam");
driver.findElement(By.name("UserFirstName")).sendKeys("sam");`
When I am using
driver.findElement(By.id("UserFirstName-m8NQ")).sendKeys("sam");
Or
driver.findElement(By.xpath("//*[#id='UserFirstName-m8NQ']")).sendKeys("sam");
I get the following error:
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[#id='UserFirstName-m8NQ']"}
In case I use By.name I am not getting any error. Here the example:
driver.findElement(By.name("UserFirstName")).sendKeys("sam");
Try the below xpath.
//input[contains(#id, 'UserFirstName')]
When you use dynamic content that appends with id, It changes frequently.
By the way, I could able to find using the xpath,
//input[#id='UserFirstName-Q2n8']

How to Use ThreadLocal<WebDriver> in Page Object Model

I have been working on this automation project for 2 years and now I am trying to implement parallel testing with ThreadLocal. I have done a lot of research on this and I have implemented ThreadLocal driver = new ThreadLocal<>(); in my BaseTestClass. My problem is I am using the page object model where each page is a class with objects. Eclipse is saying change constructor to
public LoginLogoutPage(ThreadLocal<WebDriver> driver) {
this.driver = driver;
}
I do that then I am prompted to change WebDriver driver; to ThreadLocal driver. After I do that all my fluent wait have a red line under them saying
"The constructor FluentWait<WebDriver>(ThreadLocal<WebDriver>) is undefined"
However I do not know how to fix this. Here is a snippet below.
public class BaseTestCriticalScenarios {
protected static ThreadLocal<WebDriver> driver = new ThreadLocal<>();
#BeforeClass
public void setUp() throws InterruptedException, MalformedURLException {
// --------Extent Report--------
report = ExtentManager.getInstance();
// -----------------------------
System.setProperty("webdriver.chrome.driver", "C:\\GRID\\chromedriver.exe");
ChromeOptions option = new ChromeOptions();
// --https://stackoverflow.com/questions/43143014/chrome-is-being-controlled-by-automated-test-software
option.setExperimentalOption("useAutomationExtension", false);
option.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
// --https://stackoverflow.com/questions/56311000/how-can-i-disable-save-password-popup-in-selenium
option.addArguments("--disable-features=VizDisplayCompositor");
option.addArguments("--start-maximized");
option.addArguments("--disable-gpu");
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("credentials_enable_service", false);
prefs.put("profile.password_manager_enabled", false);
option.setExperimentalOption("prefs", prefs);
System.out.println(System.getenv("BUILD_NUMBER"));
String env = System.getProperty("BUILD_NUMBER");
if (env == null) {
DesiredCapabilities capability = DesiredCapabilities.chrome();
capability.setCapability(CapabilityType.BROWSER_NAME, "Chrome");
capability.setCapability(ChromeOptions.CAPABILITY, option);
option.merge(capability);
driver.set(new RemoteWebDriver(new URL(COMPLETE_NODE_URL), capability));
getDriver().get(HOME_PAGE);
getDriver().manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
} else {
driver.set(new ChromeDriver(option));
getDriver().manage().window().maximize();
getDriver().get(HOME_PAGE);
getDriver().manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
}
public WebDriver getDriver() {
//Get driver from ThreadLocalMap
return driver.get();
}
Below is my page object class
Any help would be appreciated.

java.lang.NullPointerException when using webdriver manager selenium java

While using selenium with java, WebdriverManager is not running and the below code is giving null pointer exception. I have returned the driver at end of class.
I have one ask whether should I keep the Webdriver driver as static or not.
import io.github.bonigarcia.wdm.WebDriverManager;
public class Browserselector {
public WebDriver driver;
public static Properties prop;
public WebDriver initializeDriver() throws IOException {
{
String browserName = "firefox";
System.out.println(browserName);
if (browserName.contains("Chrome")) {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
} else if (browserName.contains("IE")) {
WebDriverManager.iedriver().setup();
driver = new InternetExplorerDriver();
} else if (browserName.contains("FireFox")) {
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
} else if (browserName.contains("EDGE")) {
WebDriverManager.edgedriver().setup();
driver = new EdgeDriver();
}
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("google.com");
return driver;
}
}
Thanks for your help in advance.
you are trying to start "firefox" - but the if condition checks for "Firefox", if you want to use it like that change the following condition
browserName.contains("FireFox")
into
browserName.equalsIgnoreCase("FireFox")
I recommend you to change the nested if with a "switch" it's more readable and easy to follow/understand
Also, don't use a URL without specifying the protocol
driver.get("https://www.google.com");

Selenium PageObject throws Invocation Target Exception

I am trying to create a framework(Selenium+TestNg+java) for a Web app(The environment is MacOs+ChromeDriver and the driver server is in \usr\local\bin) but got stuck in basic structure. I have a class(Driversetup.java) that starts the browser, another one that contains WebElements and methods(ProfileUpdateObjects.java) and the third one containing test methods. Now, when I try to run this TestNG class having just a single method, I get following exception.
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at org.openqa.selenium.support.PageFactory.instantiatePage(PageFactory.java:138).
Below is the code (All the classes are in different packages).
public class ProfileUpdateTest {
#Test(enabled = true, priority = 1)
public void profileUpdate() throws MalformedURLException, InterruptedException, ParseException {
WebDriver driver = DriverSetup.startBrowser("chrome");
ProfileUpdateObjects pu = PageFactory.initElements(driver, ProfileUpdateObjects.class);
pu.navigateProfile();
}
}
The code for ProfileUpdateObject class
public class ProfileUpdateObjects {
WebDriver driver;
public ProfileUpdateObjects(WebDriver cdriver) {
this.driver = cdriver;
}
#FindBy(xpath = " //div[#class='ico-menu']")
private WebElement menu;
#FindBy(xpath = "//a[#title='My Dashboard']")
private WebElement myDashboard;
#FindBy(xpath = " //a[contains(text(),'View Profile')]")
public WebElement profile;
#FindBy(xpath = "//li[contains(text(),'Permanent Address')]")
private WebElement permanentAddress;
#FindBy(xpath = "//li[contains(text(),'Banking Information')]")
private WebElement bankingInformation;
WebDriverWait waitfor = new WebDriverWait(driver, 2000);
public void navigateProfile() throws InterruptedException {
menu.click();
profile.click();
waitfor.until(ExpectedConditions.visibilityOf(permanentAddress));
}
}
DriverSetup.java
public class DriverSetup {
public static WebDriver driver;
public static WebDriver startBrowser(String browserName, String url) {
if (browserName.equalsIgnoreCase("chrome")) {
driver = new ChromeDriver();
}
driver.manage().window().maximize();
driver.get(url);
return driver;
}
}
It is failing in pu.navigateProfile() call. Also, is it true that #FindBy takes more memory compared to driver.find() syntax and besides POM are there any other design principles for Automation framework because most of the resources over Web are one or the other implementation of POM.
Simple solution is to move new WebDriverWait. It should not be instantiated as instance variable.
Instead of:
WebDriverWait waitfor = new WebDriverWait(driver, 2000);
public void navigateProfile() throws InterruptedException {
menu.click();
profile.click();
waitfor.until(ExpectedConditions.visibilityOf(permanentAddress));
}
Use:
public void navigateProfile() {
menu.click();
profile.click();
new WebDriverWait(driver, 2000).until(ExpectedConditions.visibilityOf(permanentAddress));
}
This will solve your issue (Already tested it)

WebDriver is not being instantiated in Cucumber tests

I'm trying to instantiate a single instance of WebDriver to use throughout some tests and, in doing so, I may have over complicated. I think I just need to instantiate a static webdriver and then re-use once for each feature file, assuming that's possible.
I'm not clear why the driver is not being instantiated. I am trying to Debug by running from feature file in the IDE (intelliJ). I'm expecting driver to instantiate when Super is called.
Step Defs:
public class FindAHolidayStepDefs extends DriverBase {
private HolidaysHomePage tcHomePage;
private SearchResultsPage searchPage;
#Before //this is the cucumber #Before
public void setup(){
holHomePage = new HolidaysHomePage(driver);
searchPage = new SearchResultsPage(driver);
}
#Given("^I am on the Holidays homepage$")
public void IAmOnTheHolidaysHomepage() {
assertEquals("the wrong page title was displayed !", "Cheap Travel\u00ae : Cheap Holidays & Last Minute Package Deals", holHomePage.getTitle());
} // more step defs below...
PageObject:
public class HolidaysHomePage extends SeleniumBase {
public HolidaysHomePage(WebDriver driver) {
super(driver); //Expecting driver to instantiate here
visit("");
driver.manage().window().maximize();
assertTrue("The Holidays header logo is not present",
isDisplayed(headerLogo));
}
//code...
DriverBase:
public class DriverBase implements Config {
protected WebDriver driver;
#Before //this is the Junit #Before
public void before() throws Throwable {
if (host.equals("localhost")) {
switch (browser) {
case "firefox":
driver = new FirefoxDriver();
break;
case "chrome":
System.setProperty("webdriver.chrome.driver",
System.getProperty("user.dir") + "\\drivers\\chromedriver.exe");
driver = new ChromeDriver();
break;
}
}
}
#After
public void after() {
driver.quit();
}
};
SeleniumBase (just a class with Selenium API methods abstracted out)
public class SeleniumBase implements Config {
public WebDriver driver;
public SeleniumBase(WebDriver driver) {
this.driver = driver;
}
public void visit(String url) {
if (url.contains("http")) {
driver.get(url);
} else {
driver.get(baseUrl + url);
}
}
Config:
public interface Config {
final String baseUrl = System.getProperty("baseUrl", "http://holidaystest.co.uk/");
final String browser = System.getProperty("browser", "chrome");
final String host = System.getProperty("host", "localhost");
}
Based on your code, here are my suggestions:
You do not need to have a DriverBase class as you already created a SeleniumBase class
Move the below driver initialization code to setup() method in FindAHolidayStepDefs
FindAHolidayStepDefs should extend SeleniumBase
if (host.equals("localhost")) {
switch (browser) {
case "firefox":
driver = new FirefoxDriver();
break;
case "chrome":
System.setProperty("webdriver.chrome.driver",
System.getProperty("user.dir") + "\\drivers\\chromedriver.exe");
driver = new ChromeDriver();
break;
}
}

Categories

Resources