Selenium version : 3.4.0
phantomjs version : 2.1.1
java : 1.8.0_151
I have tried below things but it didnt work for me.
enter code here
1:
webDriver instanceof PhantomJSDriver){
JavascriptExecutor je = (JavascriptExecutor) driver;
je.executeScript("window.alert = function(){};");
je.executeScript("window.confirm = function(){return true;};");
System.out.println("Alert has been handled"); }
else {
Alert a1 = driver.switchTo().alert();
a1.accept();
}
2:
/*((PhantomJSDriver)driver).executeScript("window.alert = function(){}");
((PhantomJSDriver)driver).executeScript("window.confirm = function(){return true;}");*/
3:
PhantomJSDriver phantom = (PhantomJSDriver) driver;
phantom.executeScript("window.confirm = function(){return true;};");
4:
((JavascriptExecutor)driver).executeScript("window.alert = function(msg){};");
((JavascriptExecutor)driver).executeScript("window.confirm = function(msg){return true;};");
5 :
PhantomJSDriver phantom = (PhantomJSDriver)driver;
phantom.executePhantomJS("var page = this;" +
"page.onAlert = function(msg) {" +
"console.log('ALERT: ' + msg);" +
"};");
phantom.executePhantomJS("var page = this;" +
"page.onConfirm = function(msg) {" +
"console.log('CONFIRM: ' + msg);"+ "return true;" +"};");
Can you please suggest apart from above.
To handle alert in PhantomJS you have to wait for the alert to be present and then cast the WebDriver to JavascriptExecutor. You can use can use the following code block :
((JavascriptExecutor) driver).executeScript("window.alert = function(msg){};");
//or
((JavascriptExecutor) driver).executeScript("window.confirm = function(msg){return true;};");
driver.findElement(By.id("element_which_trigers_the_alert")).click();
Related
I am testing a angularjs page and using selenium(java) to write automation scripts for the same.
The following is the code that I use for the page synchronization wait before proceeding to next screen action
public static boolean angularHasFinishedProcessing() {
ExpectedCondition<Boolean> pageLoadCondition = new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driver) {
driver = GetDriver();//This is to get the driver in current action.
String hasAngularFinishedScript = "var callback = arguments[arguments.length - 1];\n" +
"var el = document.querySelector('html');\n" +
"if (!window.angular) {\n" +
"console.log('1'); \n" +
" callback('false')\n" +
"}\n" +
"if (angular.getTestability) {\n" +
" angular.getTestability(el).whenStable(function(){callback('true')});\n" +
"} else {\n" +
"console.log('hello3'); \n" +
" if (!angular.element(el).injector()) {\n" +
" callback('false')\n" +
" }\n" +
" var browser = angular.element(el).injector().get('$browser');\n" +
" browser.notifyWhenNoOutstandingRequests(function(){callback('true')});\n" +
"}";
JavascriptExecutor javascriptExecutor = (JavascriptExecutor) driver;
String isProcessingFinished = javascriptExecutor.executeAsyncScript(hasAngularFinishedScript).toString();
return Boolean.valueOf(isProcessingFinished);
}
};
WebDriverWait wait = new WebDriverWait(driver, 60);
boolean bRet = (wait.until(pageLoadCondition));
if (bRet) {
return bRet;
} else
return false;
}
The issue is isProcessingFinished is always false, the console always writes 1 (meaning window.angular always returns false).
Also, Since, there is no way I can debug the javascript snippet during the execution, I don't know if there is any other issue. Could someone help please?
1) For how to debug javascript
Add a breakpoint before this wait function, run script until stopped at this breakpoint, Open DevTool of browser and execute window.angular in console Tab to see it's true or false.
And you can continue to execute the rest code lines of your javascript snippet in console Tab to examine any code issue or work as expect.
I have been trying to use PhantomJSWebDriver framework for automating an application using Headless browser. The main issue is as we can successfully switch between windows in firefox or IE windows, here I am not able to switch between windows based on handles. Please help me.
Below is the code I have tried so far.
System.setProperty("phantomjs.binary.path", file.getAbsolutePath());
driver = new PhantomJSDriver();
driver.get(application url);
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
WebElement txtUsername = driver.findElement(By.id("it_C_C5"));
txtUsername.sendKeys("sreenis");
WebElement txtPassword = driver.findElement(By.id("it_C_C7"));
txtPassword.sendKeys("sreeni");
WebElement btnLogin = driver.findElement(By.id("ic_C_C8"));
btnLogin.click();
Thread.sleep(10000);
String winTitle = "Role profile selection";
boolean bool = switchWindow(winTitle);
if (bool){
System.out.println("Page title is: " + driver.getTitle());
driver.quit();
}
else {
System.out.println("Switch to window '" + winTitle + "' failed!");
driver.quit();
}
public static boolean switchWindow(String windowtitle){
String mainWindowsHandle = driver.getWindowHandle();
Set<String> handles = driver.getWindowHandles();
System.out.println(handles.size());
for(String winHandle : handles){
driver.switchTo().window(winHandle);
System.out.println(driver.getTitle());
if(driver.getTitle().toLowerCase().equals(windowtitle)){
return true;
}
}
driver.switchTo().window(mainWindowsHandle);
return false;
}
When I tried to print the window titles in collection, it is only printing the parent window and not the other windows. I am not able to guess what is happening since nothing can be seen and it is headless testing. Please suggest me is there any other way so that I can test the app with many browser windows.
Actions act = new Actions(d);
act.contextClick(elements).sendKeys("W").perform();
Set<String> win = d.getWindowHandles();
Iterator <String> itrwin = win.iterator();
String parent = itrwin.next();
String child = itrwin.next();
d.switchTo().window(child);
identify an web element first using findElement() and store it in element.
if I use a web driver then it works perfectly
driver = new PhantomJSDriver(capabilities);
driver.executePhantomJS( "var page = this;");
How can I make it work?
driver = new RemoteWebDriver(capabilities);
driver.executePhantomJS( "var page = this;");
UPDATE
My code
capabilities = DesiredCapabilities.phantomjs();
driver = new RemoteWebDriver(capabilities);
driver.executePhantomJS( "var page = this; binary =0;mimetype=''; count = 0;id=0; bla = '{';"
+"page.onResourceReceived = function(request) {"
+ "if(id !== request.id){"
+"bla += '\"'+count+ '\":'+JSON.stringify(request, undefined, 4)+',';"
+"if(request.contentType.substring(0, 11) =='application'){"
+"console.log(request.contentType);"
+ "mimetype = request.contentType;"
+ "binary++;"
+ "}"
+"count++;"
+ "id = request.id;"
+ "}"
+"};");
Java gives error: The method executePhantomJS(String) is undefined for the type RemoteWebDriver.
If i use executeScript it will not work.
I need run 100 test parallel, i can't use webdriver.
I guess that you wanna run PhantomJSDriver on your Se Grid. This is how it works for me (C# Factory implementation):
public IWebDriver CreateWebDriver(string identifier)
{
if (identifier.ToLower().Contains("ghostdriver"))
{
return new RemoteWebDriver(new Uri(ConfigurationManager.AppSettings["Selenium.grid.Url"]), DesiredCapabilities.PhantomJS());
}
}
or try this one
Console.WriteLine("Creating GhostDriver (PhantomJS) driver.");
//Temporary commented for testing purposes
IWebDriver ghostDriver = new PhantomJSDriver("..\\..\\..\\MyFramework\\Drivers");
ghostDriver.Manage().Window.Maximize();
//ghostDriver.Manage().Window.Size = new Size(1920, 1080);
ghostDriver.Manage()
.Timeouts()
.SetPageLoadTimeout(new TimeSpan(0, 0, 0,
Convert.ToInt32(ConfigurationManager.AppSettings["Driver.page.load.time.sec"])));
return ghostDriver;
In case that you wonder why there is ConfigurationManager - I avoid the hard-coded values, so they are extracted from the App.config file.
If you want to run PhantomJS scripts with RemoteWebDriver (for using the Selenium Grid), I used the following solution (only C# unfortunately):
I had to extend the RemoteWebDriver so it can run PhantomJS commands:
public class RemotePhantomJsDriver : RemoteWebDriver
{
public RemotePhantomJsDriver(Uri remoteAddress, ICapabilities desiredCapabilities) : base(remoteAddress, desiredCapabilities)
{
this.CommandExecutor.CommandInfoRepository.TryAddCommand("executePhantomScript", new CommandInfo("POST", $"/session/{this.SessionId.ToString()}/phantom/execute"));
}
public Response ExecutePhantomJSScript(string script, params object[] args)
{
return base.Execute("executePhantomScript", new Dictionary<string, object>() { { "script", script }, { "args", args } });
}
}
After this you can use the ExecutePhantomJSScript method to run any JavaScript code that wants to interact with the PhantomJS API. The following example gets the page title trough the PhantomJS API (Web Page Module):
RemotePhantomJsDriver driver = new RemotePhantomJsDriver(new Uri("http://hub_host:hub_port/wd/hub"), DesiredCapabilities.PhantomJS());
driver.Navigate().GoToUrl("http://stackoverflow.com");
var result = driver.ExecutePhantomJSScript("var page = this; return page.title");
Console.WriteLine(result.Value);
driver.Quit();
I want to get session variable and cookies after login. i have used selenium webdriver and successfully login. but how to get session and cookies after login in selenium.here is my code:
try {
WebDriver driver = new FirefoxDriver();
driver.get("https://pacer.login.uscourts.gov/csologin/login.jsf");
System.out.println("the title is"+driver.getTitle());
WebElement id= driver.findElement(By.xpath("/html/body/div[3]/div/div[1]/div[1]/div[15]/div[2]/form/table[1]/tbody/tr/td[2]/input"));
WebElement pass=driver.findElement(By.xpath("/html/body/div[3]/div/div[1]/div[1]/div[15]/div[2]/form/table[2]/tbody/tr/td[2]/input"));
WebElement button=driver.findElement(By.xpath("/html/body/div[3]/div/div[1]/div[1]/div[15]/div[2]/form/div[2]/button[1]"));
id.sendKeys("USERNAME");
pass.sendKeys("PASSWORD");
button.click();
} catch (Exception e) {
e.printStackTrace();
}
please provide your suggestion asap.
Thanks
I ran your code with the following code additions and was able to get the following value in my console.
try {
WebDriver driver = new FirefoxDriver();
driver.get("https://pacer.login.uscourts.gov/csologin/login.jsf");
System.out.println("the title is" + driver.getTitle());
WebElement id = driver
.findElement(By
.xpath("/html/body/div[3]/div/div[1]/div[1]/div[15]/div[2]/form/table[1]/tbody/tr/td[2]/input"));
WebElement pass = driver
.findElement(By
.xpath("/html/body/div[3]/div/div[1]/div[1]/div[15]/div[2]/form/table[2]/tbody/tr/td[2]/input"));
WebElement button = driver
.findElement(By
.xpath("/html/body/div[3]/div/div[1]/div[1]/div[15]/div[2]/form/div[2]/button[1]"));
id.sendKeys("USERNAME");
pass.sendKeys("PASSWORD");
button.click();
Thread.sleep(10000);
Set<Cookie> cookies = driver.manage().getCookies();
System.out.println("Size: " + cookies.size());
Iterator<Cookie> itr = cookies.iterator();
while (itr.hasNext()) {
Cookie cookie = itr.next();
System.out.println(cookie.getName() + "\n" + cookie.getPath()
+ "\n" + cookie.getDomain() + "\n" + cookie.getValue()
+ "\n" + cookie.getExpiry());
}
} catch (Exception e) {
e.printStackTrace();
}
console
the title isPACER Login
Size: 1
JSESSIONID
/csologin/
pacer.login.uscourts.gov
E44C8*********************400602
null
Instead of Thread.sleep(10000) you can also try using explicit wait. I believe that the web page took some time to set the cookies since it was busy waiting for the page to load.
Hope this helps you.
I want to use JavaScript with WebDriver (Selenium 2) using Java.
I've followed some a guide and on Getting Started page: there is an instruction at 1st line to run as:
$ ./go webdriverjs
My question: From which folder/location the command mentioned above will be run/executed?
Based on your previous questions, I suppose you want to run JavaScript snippets from Java's WebDriver. Please correct me if I'm wrong.
The WebDriverJs is actually "just" another WebDriver language binding (you can write your tests in Java, C#, Ruby, Python, JS and possibly even more languages as of now). This one, particularly, is JavaScript, and allows you therefore to write tests in JavaScript.
If you want to run JavaScript code in Java WebDriver, do this instead:
WebDriver driver = new AnyDriverYouWant();
if (driver instanceof JavascriptExecutor) {
((JavascriptExecutor)driver).executeScript("yourScript();");
} else {
throw new IllegalStateException("This driver does not support JavaScript!");
}
I like to do this, also:
WebDriver driver = new AnyDriverYouWant();
JavascriptExecutor js;
if (driver instanceof JavascriptExecutor) {
js = (JavascriptExecutor)driver;
} // else throw...
// later on...
js.executeScript("return document.getElementById('someId');");
You can find more documentation on this here, in the documenation, or, preferably, in the JavaDocs of JavascriptExecutor.
The executeScript() takes function calls and raw JS, too. You can return a value from it and you can pass lots of complicated arguments to it, some random examples:
1.
// returns the right WebElement
// it's the same as driver.findElement(By.id("someId"))
js.executeScript("return document.getElementById('someId');");
// draws a border around WebElement
WebElement element = driver.findElement(By.anything("tada"));
js.executeScript("arguments[0].style.border='3px solid red'", element);
// changes all input elements on the page to radio buttons
js.executeScript(
"var inputs = document.getElementsByTagName('input');" +
"for(var i = 0; i < inputs.length; i++) { " +
" inputs[i].type = 'radio';" +
"}" );
JavaScript With Selenium WebDriver
Selenium is one of the most popular automated testing suites.
Selenium is designed in a way to support and encourage automation testing of functional aspects of web based applications and a wide range of browsers and platforms.
public static WebDriver driver;
public static void main(String[] args) {
driver = new FirefoxDriver(); // This opens a window
String url = "----";
/*driver.findElement(By.id("username")).sendKeys("yashwanth.m");
driver.findElement(By.name("j_password")).sendKeys("yashwanth#123");*/
JavascriptExecutor jse = (JavascriptExecutor) driver;
if (jse instanceof WebDriver) {
//Launching the browser application
jse.executeScript("window.location = \'"+url+"\'");
jse.executeScript("document.getElementById('username').value = \"yash\";");
// Tag having name then
driver.findElement(By.xpath(".//input[#name='j_password']")).sendKeys("admin");
//Opend Site and click on some links. then you can apply go(-1)--> back forword(-1)--> front.
//Refresheing the web-site. driver.navigate().refresh();
jse.executeScript("window.history.go(0)");
jse.executeScript("window.history.go(-2)");
jse.executeScript("window.history.forward(-2)");
String title = (String)jse.executeScript("return document.title");
System.out.println(" Title Of site : "+title);
String domain = (String)jse.executeScript("return document.domain");
System.out.println("Web Site Domain-Name : "+domain);
// To get all NodeList[1052] document.querySelectorAll('*'); or document.all
jse.executeAsyncScript("document.getElementsByTagName('*')");
String error=(String) jse.executeScript("return window.jsErrors");
System.out.println("Windowerrors : "+error);
System.out.println("To Find the input tag position from top");
ArrayList<?> al = (ArrayList<?>) jse.executeScript(
"var source = [];"+
"var inputs = document.getElementsByTagName('input');"+
"for(var i = 0; i < inputs.length; i++) { " +
" source[i] = inputs[i].offsetParent.offsetTop" + //" inputs[i].type = 'radio';"
"}"+
"return source"
);//inputs[i].offsetParent.offsetTop inputs[i].type
System.out.println("next");
System.out.println("array : "+al);
// (CTRL + a) to access keyboard keys. org.openqa.selenium.Keys
Keys k = null;
String selectAll = Keys.chord(Keys.CONTROL, "a");
WebElement body = driver.findElement(By.tagName("body"));
body.sendKeys(selectAll);
// Search for text in Site. Gets all ViewSource content and checks their.
if (driver.getPageSource().contains("login")) {
System.out.println("Text present in Web Site");
}
Long clent_height = (Long) jse.executeScript("return document.body.clientHeight");
System.out.println("Client Body Height : "+clent_height);
// using selenium we con only execute script but not JS-functions.
}
driver.quit(); // to close browser
}
To Execute User-Functions, Writing JS in to a file and reading as String and executing it to easily use.
Scanner sc = new Scanner(new FileInputStream(new File("JsFile.txt")));
String js_TxtFile = "";
while (sc.hasNext()) {
String[] s = sc.next().split("\r\n");
for (int i = 0; i < s.length; i++) {
js_TxtFile += s[i];
js_TxtFile += " ";
}
}
String title = (String) jse.executeScript(js_TxtFile);
System.out.println("Title : "+title);
document.title & document.getElementById() is a property/method available in Browsers.
JsFile.txt
var title = getTitle();
return title;
function getTitle() {
return document.title;
}
You can also try clicking by JavaScript:
WebElement button = driver.findElement(By.id("someid"));
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].click();", button);
Also you can use jquery. In worst cases, for stubborn pages it may be necessary to do clicks by custom EXE application. But try the obvious solutions first.
I didn't see how to add parameters to the method call, it took me a while to find it, so I add it here.
How to pass parameters in (to the javascript function), use "arguments[0]" as the parameter place and then set the parameter as input parameter in the executeScript function.
driver.executeScript("function(arguments[0]);","parameter to send in");
If you want to read text of any element using javascript executor, you can do something like following code:
WebElement ele = driver.findElement(By.xpath("//div[#class='infaCompositeViewTitle']"));
String assets = (String) js.executeScript("return arguments[0].getElementsByTagName('span')[1].textContent;", ele);
In this example, I have following HTML fragment and I am reading "156".
<div class="infaCompositeViewTitle">
<span>All Assets</span>
<span>156</span>
</div>
Following code worked for me:
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.springframework.beans.factory.annotation.Autowired;
public class SomeClass {
#Autowired
private WebDriver driver;
public void LogInSuperAdmin() {
((JavascriptExecutor) driver).executeScript("console.log('Test test');");
}
}
I had a similar situation and solved it like this:
WebElement webElement = driver.findElement(By.xpath(""));
webElement.sendKeys(Keys.TAB);
webElement.sendKeys(Keys.ENTER);
You need to run this command in the top-level directory of a Selenium SVN repository checkout.