Is it possible to get the text inside an alert box using Phantom.js?
var page = require("webpage").create()
, assert = require("assert");
page.open("http://www.mysite.com/page", function (status) {
page.includeJs("jquery-1.10.2.min.js", function () {
var alertText = page.evaluate(function () {
//This should cause an alert dialog to appear
$('button[type="submit"]').click();
//This doesn't work, but is there some equivalent to this?
return $("alert").val();
});
assert.equal(alertText, "Thanks for clicking Submit!");
});
});
There's no way to get the message from the
alert
that way (there is no HTML element called<alert>
, which is what you're trying to find using jQuery). However, what you could do is redefinewindow.alert
to do something else like log to the console. Then you can useonConsoleMessage
to look at the console message. To distinguish it from other console messages that you can get, you can give it a unique prefix. I usedALERT:
in this case:If you don't want to go the
onConsoleMessage
route, you could create your own hiddeninput
element (in the redefinedalert
) and then simply query that value:Then in your code, instead of
jQuery("alert").val()
, you would dojQuery("#alertText").val()
.