I'm trying to handle alerts event with HtmlUnitDriver, but I have some problems, and I would like to understand why. Here is the java code:
HtmlUnitDriver browser = new HtmlUnitDriver(true);
browser.get("http://localhost:8001/index.html");
browser.findElementById("myButton").click();
try {
WebDriverWait wait = new WebDriverWait(browser, 2);
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = browser.switchTo().alert();
alert.accept();
System.out.println("ALERT");
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println("NO ALERT");
}
String htmlContent = browser.getPageSource();
System.out.println(htmlContent);
browser.close();
and this is the html code: index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<meta charset="utf-8" />
</head>
<body>
<form id="form1">
<input id="username" name="username" />
<button id="myButton" type="button" value="Page2">Go to Page2</button>
</form>
</body>
</html>
<script>
document.getElementById("myButton").onclick = function () {
location.href = "page2.html";
};
</script>
page2.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Page2</title>
<meta charset="utf-8" />
</head>
<body onload="myfunction('hello2')">
<p id="result"></p>
</body>
</html>
<script>
function myfunction(data) {
document.getElementById('result').innerHTML = data
}
</script>
The output in the console is :
NO ALERT
<?xml version="1.0" encoding="UTF-8"?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>
Page2
</title>
<meta charset="utf-8"/>
</head>
<body onload="myfunction('hello2')">
?
<p id="result">
hello2
</p>
<script>
//<![CDATA[
function myfunction(data) {
document.getElementById('result').innerHTML = data
}
//]]>
</script>
</body>
</html>
Looking at the output, it seems to be a little different from the source code, and about this I have few questions. why the alert on page2.html isn't detected? Why are there some extra characters, such as "?" and "// < ! [CDATA["? How can I avoid them?
I'm trying to handle alerts, and I'm at the beginning, so any suggestions will be appreciate.
Where are you expecting the alert to come from? The code for handling the alert looks okay, but there's nothing in the HTML that suggests that an alert will be triggered at any stage. The only script that runs on Page 2 is setting p#result
's innerHTML to 'hello2'.
As far as the extra characters are concerned, I'm not so sure. This answer might shed some light on the CDATA stuff being generated.