How can I test a "Remember Me" checkbox feature in Selenium - java

I'm trying to test the "Remember Me" functionality of a login form. I'm able to type in the user name and password, click the checkbox, click submit, and quit() or close() the browser. But when I reopen the browser with new ChromeDriver() (or any other WebDriver implementation), the test site does not remember anything because all cookies are deleted when the browser is closed and cannot be accessed when the browser is reopened.

For Chrome (config):
You have to set the path to user-dir which will save all the login info after you login for the first time. The next time you login again, login info from the user-dir will be taken.
System.setProperty("webdriver.chrome.driver", "res/chromedriver.exe");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
ChromeOptions options = new ChromeOptions();
options.addArguments("test-type");
options.addArguments("start-maximized");
options.addArguments("user-data-dir=D:/temp/");
capabilities.setCapability("chrome.binary","res/chromedriver.exe");
capabilities.setCapability(ChromeOptions.CAPABILITY,options);
WebDriver driver = new ChromeDriver(capabilities);
Login for the first time:
driver.get("https://gmail.com");
//Your login script typing username password, check 'keep me signed in' and so on
Close the driver (do NOT quit):
driver.close();
Re-initialize the driver and navigate to the site. You should not be asked for username and password again:
driver = new ChromeDriver(capabilities);
driver.get("http://gmail.com");
The above can be implemented for firefox using a firefox profile.

If the "Remember Me" feature is implemented using persistent cookies (I doubt that there is any other way to implement it), then you can actually test the feature in a cross-browser compatible way by programmatically manipulating the cookies. Cookies with an expiration date (or Expiry in the Selenium API) are persistent cookies and are stored when the browser is closed and retrieved when the browser is re-opened. Non-persistent cookies are not stored when the browser is closed. With this information, we can simulate what should happen when the browser closes, by programmatically deleting all non-persistent cookies:
// Check the "Remember Me" checkbox and login here.
Set<Cookies> cookies = webDriver.manage().getCookies();
for (Cookie cookie : cookies) {
// Simulate a browser restart by removing all non-persistent cookies.
if (cookie.getExpiry() == null) {
webDriver.manage().deleteCookie(cookie);
}
}
// Reload the login page.
webDriver.get(currentLoginPageURL);
// Assert that some text like "You are logged in as..." appears on the page to
// indicate that you are still logged in.

Related

Cant login even i am typing manually while selenium listen browser

im trying to web scrapping with selenium library in my java project. While i am try to login site with interactive behaviour (manually type username and password in login page) cant login. Site is under recaptcha protection, i think block login operation, because if i dont listen with browser with selenium, i can login.
Code;
//Webdriver
System.setProperty("webdriver.chrome.driver", "data/src/main/kotlin/com/myapp/data/drivers/chromedriver.exe");
WebDriverManager.chromedriver().setup()
//Chrome Options
val options = ChromeOptions()
// Fixing 255 Error crashes
options.addArguments("--no-sandbox")
options.addArguments("--disable-dev-shm-usage")
// Options to trick bot detection -> i can trick bot detection with this code. Site ban me if dont use this lines
options.addArguments("--disable-blink-features=AutomationControlled")
options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"))
options.setExperimentalOption("useAutomationExtension", false)
options.addArguments("window-size=1920,1080")
options.addArguments("disable-infobars")
options.addArguments("user-data-dir=/tmp/afabc")
// Changing the user agent
val userAgent = UserAgent(RandomUserAgent().getRandomUserAgent())
options.addArguments("user-agent=${userAgent}")
//Chrome Driver
val driver: WebDriver = ChromeDriver(options)
driver.manage().window().position = Point(0,0)
//Wait For Element
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(10000))
val wait = WebDriverWait(driver,60)
//Operation
driver.get(LOGIN_SITE_URL)
val afterLoginPageSomeElementXpath = "/html/body/div[1]/div[1]/div[5]/ul/li[1]/a"
//For Listen user can login or not // İf i remove this code, i can login.
wait.until(ExpectedConditions.elementToBeClickable(By.xpath(afterLoginPageSomeElementXpath)))
How can i bypass this issue? Anyone help?

Disable popup "Restore Pages? Chrome didn't shut down correctly." in selenium webdriver Java

Though I have seen some related questions, I am putting this question again as I am still facing the issue.
I have a website that asks for login verification code on first time login and then it does not ask in further login instances. If I dont use a custom browser profile, the site asks verification code every time when selenium runs the login. Hence I have used customed browser profile as below (this is not the question)
options.addArguments("user-data-dir=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data\\default");
Then, After the test is finished, I quit the browser using
driver.quit();
Problem is, next time I run the test again, the chrome browser opens with the popup "Restore Pages? Chrome didn't shut down correctly." and the site asks for verification code again after login. Entering verification code is not part my script, so the script fails. Then I close the browser manually by clicking on the X on the top corner.
Then I run the test again, chrome browser opens Normally without the popup and the site does not ask for verification code, login is successful. then, script closes browser itself by the driver.quit().
Then I run the test again, chrome browser opens with the popup and test fails again.
This shows that driver.quit() is not closing the browser correctly.
I have tried several settings, but still the popup is coming.
preferences file -> "exit_type":"none" (as well as "normal") and exit cleanly = true
site settings -> pop-ups and redirects -> Blocked (recommended)
I have also tried checking alerts exists or not, but it says "No alert". Script does not detect the popup as alert.
How can I make sure the browser is opened NORMALLY every next time after driver.quit() closes the browser in the previous test run? Please help.
Below is my code: I use chrome extension, so I cannot disable extension also.
String extFilePath = "C:\\ChromeDriver\\Salesforce_inspector.crx";
System.setProperty("webdriver.chrome.driver","C:\\chromedriver\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addExtensions(new File(extFilePath));
options.addArguments("--disable-notifications");
options.addArguments("user-data-dir=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data\\default");
options.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(options);
try
{
driver.switchTo().alert();
System.out.println("alert accepted");
} // try
catch (NoAlertPresentException Ex)
{
System.out.println("No alert");
}
driver.get("salesforce url");
I dont want to use incognito mode, because I need to retain the cookies and passwords to prevent the login verification code issue mentioned earlier.
I solved this issue setting the exit_type to normal in the preferences after set up the user dir.
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.exit_type", "Normal");
options.setExperimentalOption("prefs", prefs);
In your case will be something like this
String extFilePath = "C:\\ChromeDriver\\Salesforce_inspector.crx";
System.setProperty("webdriver.chrome.driver","C:\\chromedriver\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addExtensions(new File(extFilePath));
options.addArguments("user-data-dir=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data\\default");
options.addArguments("--start-maximized");
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.exit_type", "Normal");
options.setExperimentalOption("prefs", prefs);
WebDriver driver = new ChromeDriver(options);
try
{
driver.switchTo().alert();
System.out.println("alert accepted");
} // try
catch (NoAlertPresentException Ex)
{
System.out.println("No alert");
}
driver.get("salesforce url");

How to switch to window authentication popup and enter credentials? [duplicate]

This question already has answers here:
Selenium - Basic Authentication via url
(6 answers)
Closed 4 years ago.
After opening application URL, User is redirected to Sign-In page where there is a Sign-In button.
driver.get("abc.com")
Now when user click on Sign-In button, URL is changed in the same window say it becomes xyz.com and shows authentication popup window for login purpose similar to image shown below.
To enter username and password in authentication window I tried the below code
shell = win32com.client.Dispatch("WScript.Shell")
shell.Sendkeys("username")
time.sleep(1)
shell.Sendkeys("{TAB}")
time.sleep(1)
shell.Sendkeys("password")
time.sleep(1)
shell.Sendkeys("{ENTER}")
time.sleep(1)
It didn't work. Then I tried to open windows authentication popup directly(by copying URL after click of Sign-In button) with the above code, it worked
driver.get("xyz.com")//instead of abc.com my application URL
I am bit confused. If I open my app URL abc.com, click on Sign-In button, use autoit, it didn't enter credentials. But if I directly send window authentication URL xyz.com instead of app URL abc.com and use autoit, it work.
Can anyone suggest what I am missing here? I also tried to switch window after click on Sign-In button thinking its new URL and then autoit command, but it still it didn't work.
driver.switch_to_window(driver.window_handles[1])
Any idea on this?
Note: I noticed that click on Sign-In button, windows is loading infinitely & cursor is active on username text-field of windows authentication poup. Also once windows authentication window appears, none of selenium command is working and neither autoit command.
The dialog is treated as an alert by selenium. In c#, the code to enter in credentials for a Firefox test looks like:
// Inputs id with permissions into the Windows Authentication box
var alert = driver.SwitchTo().Alert();
alert.SendKeys( #"username" + Keys.Tab +
#"password" + Keys.Tab);
alert.Accept();
The first line is telling the driver to check for open alerts (the dialog box).
The second line sends the username and password to the alert
The third line then sends those credentials and, assuming they are valid, the test will continue.
Assuming you are testing using Firefox, there is no requirement to use extra frameworks to deal with this authentication box.
It looks like you just have to open the URL with basic auth credentials.
Can you try this first?
driver.get('http://username:password#abc.com')
If you're still getting the popup, try this
driver.get('http://username:password#xyz.com') #assuming this is the site that handles authentication
driver.get('abc.com')
It should stop the popup
you can automate the keyboard:
import keyboard
keyboard.write("username")
keyboard.press_and_release("tab")
keyboard.write("password")
keyboard.press_and_release("enter")
Here is an example of loading a login page with selenium, then entering login credentials with keyboard:
from selenium.webdriver import Firefox
import keyboard
driver = Firefox()
driver.get('https://somelink')
keyboard.press_and_release('tab')
keyboard.press_and_release('shift + tab')
keyboard.write('user', delay=1)
keyboard.press_and_release('tab')
keyboard.write('pass', delay=1)
keyboard.press_and_release('enter')
Note: keyboard may require root permission on Linux.
You need to switch to the alert, which is different than a window. Once the alert is present, you switch the alert handle, then use the .authenticate method to give it the username and password
alert = driver.switch_to.alert
alert.authenticate(username, password)
You may want to wait on the EC.alert_is_present expected condition to be sure the alert is present.
Try this (with page_title being the title of the popup window and assuming you are on a windows machine) :
from win32com.client import Dispatch
autoit = Dispatch("AutoItX3.Control")
def _window_movement_windows(page_title):
autoit.WinSetOnTop(page_title, "", 1)
autoit.WinActivate(page_title, "")
autoit.WinWaitActive(page_title)
An example how to setup AutoIt with python can be found here : Calling AutoIt Functions in Python
With Firefox, it's possible to avoid the authentication popup by automatically providing the credentials when they are requested.
It requires to inject and run some code at a browser level to detect the authentication attempt and set the credentials.
Here's a working example:
from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver
def add_credentials_moz(driver, target, username, password):
driver.execute("SET_CONTEXT", {"context": "chrome"})
driver.execute_script("""
let [target, username, password] = [...arguments];
let WebRequest = Cu.import('resource://gre/modules/WebRequest.jsm', {});
WebRequest.onAuthRequired.addListener(function listener(){
WebRequest.onAuthRequired.removeListener(listener);
return Promise.resolve({authCredentials: {username: username, password: password}});
}, {urls: new MatchPatternSet([target])}, ['blocking']);
""", target, username, password)
driver.execute("SET_CONTEXT", {"context": "content"})
WebDriver.add_credentials_moz = add_credentials_moz
driver = webdriver.Firefox()
driver.add_credentials_moz("https://httpbin.org/*", username="user", password="passwd")
driver.get("https://httpbin.org/")
driver.find_element_by_css_selector("[href='/basic-auth/user/passwd']")\
.click()

Using Selenium on https web application that runs over vpn

First of all, I need to state that I am total beginner with Selenium.
I am trying to test an application in firefox browser using Selenium. Due to security issues the application works only over vpn.
My problem occurs with the following steps; I create the webdriver and navigate to the start (login) page of application. I get an "Authorization request" popup. If I cancel the popup, then I get to a page that states "Connection is not secure" (it's https address). After I get passed that, I lose the part where Selenium program should populate username and password and it just stays on the login page.
My question, is there a way to start Selenium testing on an application so that it is already opened and prepared (ie logged in) in browser? I am not happy that username and password are hard-coded in Selenium code.
If that is not possible, how do I skip that authorization popup and problem with non-secure connection? How do I populate username and password in safest way?
Thanks!
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\Selenium-java-3.0.1\\geckodriver.exe");
// I tried also with this code bellow in comment, but it did not work, it did not even get to login page
//WebDriverWait wait = new WebDriverWait(driver, 10);
//Alert alert = wait.until(ExpectedConditions.alertIsPresent());
//alert.authenticateUsing(new UserAndPassword("cfadmin", "20lipim18"));
driver.get("https://Application_login_page.com");
driver.findElement(By.xpath(".//*[#id='login']")).click();
driver.findElement(By.xpath("[#id='login']")).sendKeys("Username");
}
if it's possible, is there a way to start Selenium testing on application that is already opened and prepared (logged) in browser?
Try using firefox profile. Since selenium open fresh instance of browser by default. You can use your own firefox frofile.
This is a code to implement a profile, which can be embedded in the selenium code.
ProfilesIni profile = new ProfilesIni();
// this will create an object for the Firefox profile
FirefoxProfile myprofile = profile.getProfile("default");
// this will Initialize the Firefox driver
WebDriver driver = new FirefoxDriver(myprofile)
It will also maintain the session means you are already login to the application in firefox(default profile). Then if you execute the script, you will see that you are already logged in to the application.
There is no way to open already authorised page, you have to have to pass username and password through selenium script.
You may use below code to do the authentication
WebDriverWait wait = new WebDriverWait(driver, 10);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.authenticateUsing(new UserAndPassword(username, password));

Selenium Webdriver - Chrome - Switch Window and back - Unable to receive message from renderer

This is my first question on Stack Overflow. Thanks to all StackOverflow users who keeps technology passion ticking.
I am testing a web application with selenium Webdriver . It is payment webpage where, after selecting Payment method as 'PayPal' it opens up a new Popup , a PayPal popup and i Switch window to Paypal , do all my necessary Transaction. And once the Transaction is successful , automatically the paypal popup is closed, and i am not able to return to my original window from where i have initiated transaction.
I am getting following error in eclipse console:
Starting ChromeDriver (v2.9.248315) on port 25947
[70.164][SEVERE]: Unable to receive message from renderer
The following details might help :
selenium Webdriver (2.28.0)
java - JRE7
Google Chrome Version - Version 33.0.1750.146
Test Framework - Test NG
Here is my code :
// To Switch to Popup/Paypal window
String currentWindowHandle=driver.getWindowHandle();
Set<String> openWindowsList=driver.getWindowHandles();
String popUpWindowHandle=null;
for(String windowHandle:openWindowsList)
{
if (!windowHandle.equals(currentWindowHandle))
popUpWindowHandle=windowHandle;
}
driver.switchTo().window(popUpWindowHandle);
// Carraying out my paypal transaction
driver.manage().window().maximize();
driver.findElement(By.xpath("//*[#id='loadLogin']")).click();
Thread.sleep(8000);
WebElement login_email = driver.findElement(By.xpath("//*[#id='login_email']"));
login_email.clear();
login_email.sendKeys(Keys.BACK_SPACE);
login_email.sendKeys("abc#abc.com");
WebElement login_password = driver.findElement(By.xpath("//*[#id='login_password']"));
login_password.clear();
login_password.sendKeys("abcxyz");
// Next Click is Final Click on PayPal
driver.findElement(By.xpath("//*[#id='submitLogin']")).click();
// Transaction is finished on PayPal side and it automatically popup is closed
//Now i am trying to switch to my last working(original) window
driver.switchTo().window("My Web Page Title");
You should be using:
driver.switchTo().window(currentWindowHandle);
It causes because page took long time to load , you need add additional line to your chromedriver option.
System.setProperty("webdriver.chrome.driver","E:\\selenium\\chromedriver_2.41\\chromedriver.exe");
//mention the below chrome option to solve timeout exception issue
ChromeOptions options = new ChromeOptions();
options.setPageLoadStrategy(PageLoadStrategy.NONE);
// Instantiate the chrome driver
driver = new ChromeDriver(options);
The problem is resolved.
The place where I was declaring currentWindowHandle was after clicking and it takes the new window as the Current Window handle.
I just moved below statement to before the new window click event.
String currentWindowHandle=driver.getWindowHandle();
Thanks all for your time and Help.

Categories