Why doesn't HtmlUnitDriver execute JavaScript? - java

I got the following problem:
I am running a JUnit testCase with Selenium 2.9 using HtmlUnitDriver with Browserversion Firefox_3_6. JavaScript is enabled. Now when it should call and execute the following javaScript function it does nothing:
function openIdsDocument()
{
var windowBounds = getWindowBounds();
var XMLHTTP = getAjaxRequestObject("XYZ.do?availableWidth="+windowBounds.width+"&availableHeight="+windowBounds.height, "", true);
if (XMLHTTP != null)
{
XMLHTTP.onreadystatechange = function alertAJAXResponse()
{
if (XMLHTTP.readyState == 4)
{
window.location.href = getContextPath() + "ABC.do";
}
};
XMLHTTP.send("timestamp=" + <%=System.currentTimeMillis()%>);
}
getLoadingState();
}
I want to get to ABC.do
If I execute my test with the FirefoxDriver it works.
Is there a way to get this working with HtmlUnitDriver?
My test works if I manually call driver.get("http://host/ABC.do") but that cannot be the right way to do this.

You can enable JavaScript by doing either
new HtmlUnitDriver(true);
driver.setJavascriptEnabled(true);
What you need to do is to wait until the JavaScript is executed after get(url).
You can use Thread.sleep() method for adding some delay.
HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.FIREFOX_3_6);
driver.setJavascriptEnabled(true);
driver.get(url);
Thread.sleep(100);
runTest();
Update
As #Corey indicated in the comments, it could be nicer to use Explicit and Implicit Waits instead of Thread.sleep(). As I don't use them these days, I cannot confirm, though. It would be great if someone test them and update this answer.

You need to initialize the HtmlUnitDriver with enable javascript true
new HtmlUnitDriver(true);

If you wish to set the BrowserVersion as well as enable Javascript with HtmlUnitDriver, your initialization needs to look like the following (as there is no way to do both via the constructor):
HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.FIREFOX_3_6);
driver.setJavascriptEnabled(true);
This will allow you to use the browser definition of your choice and use Javascript.

You may need to do this:
WebDriver driver = new HtmlUnitDriver(BrowserVersion.INTERNET_EXPLORER_8);
((HtmlUnitDriver) driver).setJavascriptEnabled(true);

Well, There is an easy way to enable browser capability and javascript, you can do the following:
Webdriver driver = new HtmlUnitDriver(BrowserVersion.Chrome,true);
True specifies that javascript should be enabled. #Glenn Nelson,

Related

looking for option to check if page fully loaded with all elements in java for selenium

I am looking for function in Java +selenium where I can check or verify if page is fully loaded. I saw onLoad() of JS but nothing on java, is there is something for JAVA?
also I saw these:
WebDriver driver = new AnyDriverYouWant();
if (driver instanceof JavascriptExecutor) {
((JavascriptExecutor)driver).executeScript("yourScript();");
} else {
throw new IllegalStateException("This driver does not support JavaScript!");
}
but again JS and need to write script in JS
How to use JavaScript with Selenium WebDriver Java
update - also can try these solution too:
void waitForLoad(WebDriver driver) {
new WebDriverWait(driver, 30).until((ExpectedCondition<Boolean>) wd -> ((JavascriptExecutor) wd).executeScript("return document.readyState").equals("complete")); }
from here https://stackoverflow.com/a/15124562/12115696
In order to determine if a page is fully loaded, you will need to identify which WebElements on the page indicate a loading status. For example, if there is a load mask of some type, you will want to wait until the load mask is hidden to verify that the page is fully loaded.
Here's a simple "Wait until loaded" function that utilizes the ExpectedConditions class:
Given the following HTML for a load mask:
<div id='load-mask' style='display: block'/>
You can use the following code to wait until the load mask is hidden:
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(seconds));
wait.Until(ExpectedConditions.InvisibilityOfElementLocated(By.Id("load-mask")));
Edit -- added a JavaScript-only wait function, as requested by the asker:
wait.until(driver=> ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete"));
This checks the document.readyState attribute in JavaScript, and completes the wait once readyState is set to complete.

Click is happening some other place on Cart ICON in MSITE from appium code - Chrome browser

I am trying to click on cart icon on top right corner from Appium in chrome browser mobile.
Code to click :
driver.findElement(By.xpath("//a[#href='/viewcart']")).click();
URL : https://www.2gud.com/?cmpid=2G108229
Note: Please open this URL in mobile device and verify.
Error : Code is clicking somewhere else on mobile device.
This is working. Checked in Android 7.1 emulator
driver.findElement(By.xpath("//a[#href='/rv/viewcart']")).click();
public class Demo {
public static WebDriver driver = null;
public static void main(String args[]) throws InterruptedException {
System.out.println("Launching the chrome driver ");
System.setProperty("webdriver.chrome.driver","src\\test\\resources\\drivers\\chromedriver40.exe");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("androidPackage", "com.android.chrome");
driver = new ChromeDriver(options);
driver.manage().timeouts().pageLoadTimeout(20,TimeUnit.SECONDS);
driver.get("https://www.2gud.com/?cmpid=2G108229");
Thread.sleep(3000);
driver.findElement(By.xpath("//a[#href='/rv/viewcart']")).click();
Thread.sleep(3000);
System.out.println(driver.getTitle());
driver.quit();
}
Try to click using mouse actions or JavaScript executor.
Try using the following code.
Xpath to find the view cart: //a[contains(#href,'viewcart')]
Executing a click via JavaScript has some behaviors of which you should be aware. If, for example, the code bound to the onclick event of your element invokes window.alert(), you may find your Selenium code hanging, depending on the implementation of the browser driver. That said, you can use the JavascriptExecutor class to do this. My solution differs from others proposed, however, in that you can still use the WebDriver methods for locating the elements.
// Assume driver is a valid WebDriver instance that has been properly instantiated elsewhere.
WebElement viewCart = driver.findElement(By.xpath("//a[contains(#href,'viewcart')]"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", viewCart);
You should also note that you might be better off using the click() method of the WebElement interface, but disabling native events before instantiating your driver. This would accomplish the same goal (with the same potential limitations), but not force you to write and maintain your own JavaScript.

How to know webDriver opened URL successfully

How to know WebDriver opened an URL successfully after driver.get(appURL)? I can see it opens nicely in a browser. But I would like to make sure programmatically.
Hey. Here I am asking whether driver.get(appURL) returns any response code like http response. Or I have to find a ID from the web page and find it, then make conclusion, but the approach seems too primitive. I am looking for more simple solution. Someone suggested assertTrue, but some reason Eclipse is giving long error.
The simplest way to do so, would be to assert over the page title of the url you have opened :
String actualTitle = driver.getTitle();
String expectedTitle = "YourExpectedPage"; // replace with the expected page title
org.junit.Assert.assertTrue(expectedTitle.equals(actualTitle));
you can wait some time and check expected result then check current url
String currentURL = null;
WebDriverWait wait = new WebDriverWait(driver, 10);
if(driver.findElement(By.xpath("//*[#id='someID']")).isDisplayed()){ //add id or xpath
currentURL = driver.getCurrentUrl();
System.out.println(currentURL);
}
Each browser has a default error page. For chrome i am using:
if(driver.findElement(By.xpath("//div[#class='error-code']")).isDisplayed()){
MessageBox.Show("chrome error page.");
}
Try this with simple statements
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
String baseUrl="https://stackoverflow.com/";
driver.get(baseUrl);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
if(baseUrl.equals(driver.getCurrentUrl()))
{
System.out.println("URLS are matching");
}else
{
System.out.println("URLS are not matching");
}
As a End User we really don't have to be concerned about whether WebDriver instance opened an URL successfully or not because once the WebDriver instance requests for a URL, the Browser Client on opening the webpage/website (by default) returns document.readyState as complete to the WebDriver instance and only then our next line of code gets executed.
However, as an End User we can configure the WebDriver instance to act on different available states of the DOM as well. Currently Selenium recognizes document.readyState at 3 different stages as follows:
none - The document is still loading
eager - The document is interactive
normal - The document is complete
Hence our scripts can be written to configure the WebDriver instance to respond as per your requirement.

Headless/GUIless automation with Selenium Webdriver

I would like to save some resources on my low-spec Windows boxes by running the browser in a headless mode. As far as I am aware, PhantomJS + GhostDriver is the standard choice for such task to be used with Selenium Webdriver. However after trying it and immediately running into issues with alerts handling which doesn't seem to be supported by PhantomJS. Specifically, the following exception is returned:
[ERROR - 2016-08-01T04:24:24.894Z] RouterReqHand - _handle.error - {"name":"Invalid Command Method"," . . . "}
as a result of not supporting getAlertText WebDriver Command when performing:
Alert alert = driver.switchTo().alert();
and specifically this method implemented in EventFiringWebDriver:
public Alert alert() {
return targetLocator.alert();
}
I am looking for an alternative approach or a feasible workaround. Anyone?
I have been able to work around that by executing the alert handling using JavaScript directly like this:
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
jsExecutor.executeScript("window.alert = function(){}");
jsExecutor.executeScript("window.confirm = function(){return true;}");
At the moment, there seem to be no way to perform that operation directly via WebDriver interface for PhantomJS.

ChromeDriver Disable Javascript in Java

https://code.google.com/p/selenium/issues/detail?id=3175
Doesn't work.
So then I tried this,
ChromeOptions opts = new ChromeOptions();
opts.addArguments("--disable-javascript");
driver = new ChromeDriver(opts);
But then driver.get(website);
javascript is enabled again. When it was on data; it was disabled.
Also I tried,
DesiredCaptabilities caps = DesiredCaptabilties.chrome();
caps.setJAvaScriptEnabled(fale);
driver = new ChromeDriver(caps);
driver.get(Website);
Nothing is working. Any advice?
javascriptEnabled just works on HTMLUnitDriver.
And ChromeDriver should have JavaScript enabled to work properly in the first place, so you canĀ“t disable JavaScript if you use ChromeDriver2.
static public void DisableJS () {
driver.get("chrome://settings");
driver.switchTo().frame("settings");
driver.findElement(By.id("advanced-settings-expander")).click();
driver.findElement(By.id("privacyContentSettingsButton")).click();
//here do not allow js
driver.findElement(By.xpath("//*[#id='content-settings-page']/div[2]/section[3]/div/div[2]/label/input")).click();
driver.findElement(By.id("content-settings-overlay-confirm")).click();
}

Categories