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

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

Related

Unable to handle this Confirmation Message - Selenium WebDriver

I am trying to Automate a web application , where I click on to next page and it throws a confirmation message which I could not handle it
I have used the below in my script
WebDriverWait wait = new WebDriverWait(Driver, 15);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.accept();
Error : Expected condition failed: waiting for alert to be present
So I think when you click on next button it open a new tab and displays
the confirmation JavaScript alert.
You can handle this for now only through Firefox geckoDriver this
is issue with the [ChromeDriver][1]
https://github.com/SeleniumHQ/selenium/issues/9040
I've tried like below, Just check it
WebDriver driver = new FirefoxDriver();
driver.navigate().
to("https://www.w3schools.com/jsref/event_onload.asp");
driver.manage().window().maximize();
WebElement element = driver.findElement(By.xpath(".
(//a[contains(text(),'Try it Yourself ยป')])[1]"));
Set<String> originalWindowHandles =driver.getWindowHandles();
((JavascriptExecutor)driver).executeScript("arguments[0].click();", element);
Set<String> updatedWindowHandles = driver.getWindowHandles();
for(String window: updatedWindowHandles)
{
if(!originalWindowHandles.contains(window)){
driver.switchTo().window(window);
break;
}
}
Thread.sleep(5000);
Alert alert = driver.switchTo().alert();
alert.accept();
}

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());

How can Selenium close Chrome browser and open new One

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.

org.openqa.selenium.remote.UnreachableBrowserException Error communicating with the remote browser phantom js

I am trying to automate gmail sending a email using selenium i am using phantom js (For headless)
I am getting the following Exception
org.openqa.selenium.remote.UnreachableBrowserException Error communicating with the remote browser
Capabilities caps = new DesiredCapabilities();
((DesiredCapabilities) caps).setJavascriptEnabled(true);
((DesiredCapabilities) caps).setCapability("takesScreenshot", true);
((DesiredCapabilities) caps).setCapability(
PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
"C:\\jars\\phantomjs-2.0.0-windows\\bin\\phantomjs.exe"
);
//File file = new File("C:/jars/phantomjs-2.0.0-windows/bin/phantomjs.exe");
// System.setProperty("phantomjs.binary.path", file.getAbsolutePath());
WebDriver d = new PhantomJSDriver(caps);
//WebDriver d=new HtmlUnitDriver();
WebDriverWait wait = new WebDriverWait(d, 10);
d.get("https://www.gmail.com/intl/en/mail/help/about.html");
System.out.println("navigated to gmail");
d.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
d.manage().window().setSize(new Dimension(1576, 798));;
d.findElement(By.id("gmail-sign-in")).click();
System.out.println("Clicked on Signin");
Thread.sleep(9000);
d.findElement(By.id("Email")).sendKeys("chaitanyapujari97#gmail.com");
System.out.println("Entered Email");
Thread.sleep(9000);
d.findElement(By.id("next")).click();
System.out.println("Clicked next");
d.findElement(By.id("Passwd")).sendKeys("your pwd");
System.out.println("Entered password");
Thread.sleep(9000);
d.findElement(By.id("signIn")).click();
System.out.println("Clicked on signin");
Thread.sleep(9000);
d.findElement(By.xpath("html/body/div[7]/div[3]/div/div[2]/div[1]/div[1]/div[1]/div[2]/div/div/div[1]/div/div")).click();
System.out.println("Clicked on Compose email");
//Thread.sleep(9000);
Thread.sleep(9000);
d.findElement(By.name("to")).sendKeys("your email");
System.out.println("Entered To address");
Thread.sleep(9000);
d.findElement(By.name("q")).click();
d.findElement(By.name("subjectbox")).sendKeys("PHANTOm Js");
System.out.println("Entered Subject");
//WebElement webElement=d.findElement(By.name("subjectbox"));
/*String keysPressed = Keys.chord(Keys.CONTROL, Keys.RETURN);
WebElement element=d.findElement(By.xpath("html/body"));
element.sendKeys(keysPressed) ;*/
Thread.sleep(9000);
d.findElement(By.xpath("html/body/div[14]/div/div/div/div[1]/div[3]/div[1]/div[1]/div/div/div/div[3]/div/div/div[4]/table/tbody/tr/td[2]/table/tbody/tr[2]/td/div/div/div[4]/table/tbody/tr/td[1]/div/div[2]")).click();
System.out.println("Clicked On send");
i am able to add the recipient email address and subject unable to click on send button.
I am not able to figure it out i am new to Headless Selenium automation please help,
Please try this , I hope it will help you , Why are you using such long XPATH , it will have to traverse from html.
d.findElement(By.xpath(".//tr[#class='n1tfz']/td[1]/div[1]/div[2]")).click();
I found it the problem was with the jar i was using the jar phantomjsdriver-1.1.0.jar i have changed the versions of jar now which is phantomjsdriver-1.2.1.jar works perfectly fine.
Thanks for the help friends.

How to close the new windows in firefox that open after extracting elements from div using webdriver?

Webdriver launches multiple windows after performing click action. I have tried driver.close() but it close the webdriver and test fails.
WebDriver driver = new FirefoxDriver ();
driver.get("http://www.xyz.com/");
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement page = driver.findElement(By.className("coupon-rows"));
List <WebElement> coupontrigger = page.findElements(By.className("code"));
System.out.println("number of couponsTriggers on carousel = "+ "coupontrigger.size());
for (int j=0; j<=coupontrigger.size(); j++) {
js.executeScript("$('.ccode.coupon-trigger').eq("+j+").click()");
System.out.println(driver.getTitle());
driver.switchTo().defaultContent();
driver.get("http://www.xyz.com/");
page = driver.findElement(By.className("coupon-rows"));
coupontrigger = page.findElements(By.className("code"));
}
}
If I understood your requirement you want to close the other popups rather than the main window. In that case you can do below. Though I am not 100% sure of your requirement.
String mwh=driver.getWindowHandle(); // Get current window handle
Set<String> s=driver.getWindowHandles();
Iterator<String> ite=s.iterator();
String popupHandle = "";
while(ite.hasNext())
{
popupHandle = ite.next().toString();
if(!popupHandle.contains(mwh)) // If not the current window then shift focus and close them
{
driver.switchTo().window(popupHandle);
driver.close();
}
}
driver.switchTo().window(mwh); // finally move control to main window.
You can introduce a helper method which will do that task for you. You just need to find out what your current view is (WebDriver#getWindowHandle will give the one you have focus on) and then just close the rest of the windows.
private String closeAllpreviouslyOpenedWindows() {
String firstWindow = webDriver.getWindowHandle();
Set<String> windows = webDriver.getWindowHandles();
windows.remove(firstWindow);
for (String i : windows) {
webDriver.switchTo().window(i);
webDriver.close();
}
webDriver.switchTo().window(firstWindow);
return firstWindow;
}

Categories

Resources