How can Selenium close Chrome browser and open new One - java

My scenario is to close the chrome browser and open a new one.
public String openNewBrowserWindow() {
this.log("Opening new Browser window...");
String stringHandles;
Set<String> previousWindows = driver.getWindowHandles();
String previousHandle = driver.getWindowHandle();
((JavascriptExecutor)driver).executeScript("window.open();");
Set<String> newWindows = driver.getWindowHandles();
newWindows.removeAll(previousWindows);
String newHandle = ((String)newWindows.toArray()[0]);
stringHandles = previousHandle + ";" + newHandle;
return stringHandles;
}
What I did is this:
String handlesA = generic.openNewBrowserWindow();
String[] handleA = handlesA.split(";");
generic.closeBrowser();
generic.switchToWindow(handleA[1]);
This works on firefox but not in chrome. Do you guys have any suggestion?

Why not just:
driver.quit()
driver = new ChromeDriver()
What is your scenario really?

#Seimone
Whenever you want to intiate a Chrome browser, system property must be defined to the chromedriver.exe
System.setProperty("webdriver.chrome.driver", driverPath+"chromedriver.exe");
WebDriver driver = new ChromeDriver();
Also, If you want to close your current chrome browser window use the following one in your code.
driver.close();
If you want to close all your chrome browser window use the following one in your code.
driver.quit();
With reference to your scenario
Open the url
Login with signed in
Close the browser
Open the browser and enter the same url
Check the same user is logged in
Try the below code and let me know your result.
String chromeDriver = "enter the chromedriver.exe path";
String chromeProfile = "C:/Users/MSTEMP/AppData/Local/Google/Chrome/User Data/Default"; //Local chrome profile path.
System.setProperty("webdriver.chrome.driver", chromeDriver);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
ChromeOptions options = new ChromeOptions();
options.addArguments("test-type");
options.addArguments("start-maximized");
options.addArguments("user-data-dir="+chromeProfile);
capabilities.setCapability("chrome.binary",chromeDriver);
capabilities.setCapability(ChromeOptions.CAPABILITY,options);
WebDriver driver = new ChromeDriver(capabilities);
driver.get("https://www.gmail.com");
/*write your login credentials code with username, password and perform the
login operation with signed in*/
driver.close();
//Now invoke the chrome browser and enter the url alone.
driver = new ChromeDriver(capabilities);
driver.get("http://www.gmail.com");
//write the code for user signed verification.

Related

How to Run Jave script in edge browser using java and selenium

i want run below code in edge browser using java selenium project
WebDriverWait wait = new WebDriverWait(driver, waitSeconds);
// wait for page complete
//log.debug("PageLoadState>>"+pageLoadCondition.toString());
// Wait for Javascript to load
ExpectedCondition<Boolean> jsLoad = driver -> ((JavascriptExecutor) driver).executeScript("return document.readyState").toString()
.equals("complete");
JavascriptExecutor js = (JavascriptExecutor) getDriver();
boolean jsReady = (Boolean) js.executeScript("return document.readyState").toString().equals("complete");
// Wait Javascript until it is Ready!
if (!jsReady) {
// System.out.println("JS in NOT Ready!");
wait.until(jsLoad);
}
we are getting exception in below line as Exception class:org.openqa.selenium.JavascriptException
the reason is:org.openqa.selenium.JavascriptException: javascript error: Function is not a constructor
boolean jsReady = (Boolean) js.executeScript("return document.readyState").toString().equals("complete");
We set edgeoption as below
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
desiredCapabilities.setBrowserName("MicrosoftEdge");
EdgeOptions edgeOptions = new EdgeOptions();
edgeOptions.setCapability("ms:inPrivate", true);
// edgeOptions.setCapability("prefs", edgePrefs);
edgeOptions.setCapability("useAutomationExtension", false);
edgeOptions.merge(desiredCapabilities);
edgeOptions.setPageLoadStrategy("eager");
edgeOptions.setCapability("ms:inPrivate", true);
edgeOptions.setCapability("useAutomationExtension", false);
edgeOptions.setCapability(CapabilityType.SUPPORTS_JAVASCRIPT, true);
edgeOptions.setCapability(CapabilityType.HAS_NATIVE_EVENTS, true);
driver = new EdgeDriver(edgeOptions);
Pls advise is any other way to run the javascript in edge using java and selenium

configuring Selenium driver to use Socks5 proxy

I'm trying to use my Socks5 proxy while using Selenium web driver here is my code :
System.setProperty("webdriver.chrome.driver", "dependencies/chromedriver.exe");
ChromeOptions options = new ChromeOptions();
Proxy prx =new Proxy() ;
prx.setSocksVersion(5);
prx.setSocksProxy("xx.xxx.xxx.xxx:8000");
prx.setSocksPassword("5xxxxS") ;
prx.setSocksUsername("VxxxxW") ;
options.addArguments("--disable-notifications");
options.addArguments("start-minimized");
options.setCapability("proxy", prx);
WebDriver driver = new ChromeDriver(options); // issue here
I'm having the following error :
Exception in thread "main" org.openqa.selenium.remote.UnreachableBrowserException: Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure.
You should add proxy server arguments to ChromeOptions:
String host = "shadowsocks6.freeproxy.center";
String port = "8989";
String socks5User = "SOCKS_USER";
String socks5Pass = "SOCKS_Pass";
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--proxy-server=socks5://" + host + ":" + port);
chromeOptions.addArguments("--proxy-auth=" + socks5User + ":" + socks5Pass);
WebDriver driver = new ChromeDriver(chromeOptions);
You can refer to selenium-tiny-projects for complete source code

Add settings to driver in selenium

Hi I am trying to add some settings to my driver in selenium but can seem to make them work.
Im trying to add
{
"DEVELOPER_MODE":false,
"AUTOMATION_MODE":true,
"AUTOMATION_LAUNCH_URL":"{whatever_url_you_want_to_test_with}"
}
to my driver file
public static WebDriver startDriverTwo() {
String projectLocation = System.getProperty("user.dir");
System.setProperty("webdriver.chrome.driver", projectLocation + "/chromedriver.exe");
ChromeOptions opt = new ChromeOptions();
opt.addArguments("start-maximized");
opt.addArguments("disable-infobars");
opt.addArguments("--disable-extensions");
opt.addArguments("--window-size=1920x1080");
opt.addArguments("--disable-cache");
//options.addArguments("--headless");
opt.addArguments("--disable-application-cache");
opt.addArguments("--disk-cache-size=0");
opt.addArguments("--disable-gpu"); // applicable to windows os only
opt.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
opt.addArguments("--dns-prefetch-disable");
opt.addArguments("--disable-notifications");
opt.addArguments("disable-infobars")
//Enter the path of your Electron app
opt.setBinary("pathtoelectronapp.exe");
driver = new ChromeDriver(opt);
System.out.println("opening app");
return driver;
}
I have tried
setExperimentalOption()
setProperty()
But neither of these work? any idea how i can work these in?
DEVELOPER_MODE - you got that right, it's opt.addArguments("--disable-extensions");
I'm little bit confused with these settings, since:
AUTOMATION_MODE - isn't this always true, when using Selenium?
AUTOMATION_LAUNCH_URL - you mean driver.get(URL) ?

How Can I get network files in google chrome with selenium?

I am using selenium for a test in a project, but I have a problem.
I need to get network files from google chrome when I inspect element.
In this section I need this files, they are JSON files, and I need its information.
//String scriptToExecute = "var performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {}; var network = performance.getEntries() || {}; return network;";
String scriptToExecute = "var network = performance.getEntries() || {}; return network;";
java.util.List<String> s= executeJavaScript(scriptToExecute)
String s attribute, return me a strange List of strange objects of the network, isn't good information for me.
This is my problem, I need JSON files, but my code returns me other things.
Use BrowserMobProxyServer along with selenium to get the network details of each network HAR format.
// Set up BrowserMobProxyServer while initiation driver
proxy = new BrowserMobProxyServer();
proxy.start(0);
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
// configure it as a desired capability
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);
driver = new ChromeDriver(capabilities);
proxy.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT);
proxy.newHar("google.com");
// Do all your navigation in selenium/ selenide code
driver.get("http://google.com");
// After navigation, you can find network details stored HAR
Har har = proxy.getHar();
If required you can store it to file before quiting the driver,
Har har = proxy.getHar();
File harFile = new File(sFileName);
har.writeTo(harFile);
proxy.stop();
driver.quit();
1.Create a webdriver with capabilities to monitor network calls too.
public static WebDriver getDriver() {
ChromeOptions options = new ChromeOptions();
System.setProperty("webdriver.chrome.driver", Driver local path);
DesiredCapabilities cap = DesiredCapabilities.chrome();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
cap.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
Map<String, Object> perfLogPrefs = new HashMap<String, Object>();
perfLogPrefs.put("traceCategories", "browser,devtools.timeline,devtools"); // comma-separated trace categories
options.setExperimentalOption("perfLoggingPrefs", perfLogPrefs);
cap.setCapability(ChromeOptions.CAPABILITY, options);
return new ChromeDriver(cap);
}
Now retrieve your log entries using following code.
for (LogEntry entry : driver.manage().logs().get(LogType.PERFORMANCE)){
System.out.println(entry.toString());
}
3.Result will be in following JSON format.
{
"webview": <originating WebView ID>,
"message": { "method": "...", "params": { ... }} // DevTools message.
}
You can use return JSON.stringify(network) replace return network.Then executeJavaScript(scriptToExecute) will return json,but it still String If you don't change to json by java.You can use org.json.Just
JSONArray netData = new JSONArray(driver.executeScript(scriptToExecute).toString());

Unable to create or switch to new tab in Selenium Webdriver with JAVA on MAC

I've tried a different options just to open new tab but all of them lead to the same result : sending char "t" to google search field.
The goal in my real test is to switch between tabs in browser, but I am unable even open new one.
Very simple test
public class LoginPhp2 {
#Test
public void testGoogle() {
WebDriver driver = new SafariDriver();
driver.get("https://www.google.com");
//driver.findElement(By.cssSelector("body")).sendKeys(Keys.COMMAND + "t");
Actions action= new Actions(driver);
action.keyDown(Keys.COMMAND).sendKeys("t").build().perform();
//action.keyDown(Keys.COMMAND).sendKeys("t").keyUp(Keys.COMMAND).build().perform();
}
}
You may use javascript to open a new tab.
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.open();");
There are different ways of opening new tabs in windows and Mac. Actual keys to send depend on your OS, for example, Mac uses COMMAND + t, instead of CONTROL + t.
You can open new tab in Mac using:
driver.findElement(By.cssSelector("body")).sendKeys(Keys.COMMAND +"t");
After this you can switch to any of the opened tabs:
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(0));
I have followed the approach suggested earlier:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.open();");
This is opening new tab in the same window. I have tried it on my MAC machine

Categories

Resources