是否可以使用 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!");
});
});
没有办法从消息中获取消息alert
这样(没有名为的 HTML 元素<alert>
,这就是您尝试使用 jQuery 查找的内容)。然而,你可以做的是重新定义window.alert
执行其他操作,例如登录到控制台。然后你可以使用onConsoleMessage
查看控制台消息。为了将其与您可以获得的其他控制台消息区分开来,您可以为其指定一个唯一的前缀。我用了ALERT:
在这种情况下:
page.evaluate(function() {
window.alert = function(str) {
console.log("ALERT:" + str);
}
});
page.onConsoleMessage(function(message, lineNumber, sourceId) {
if(/^ALERT:/.test(message)) {
//do something with message
}
});
如果你不想去onConsoleMessage
路线,您可以创建自己的隐藏路线input
元素(在重新定义的alert
)然后简单地查询该值:
page.evaluate(function() {
window.alert = function(str) {
if(jQuery("#alertText").length === 0) {
jQuery("body").append(jQuery("<input>").attr("id", "alertText").attr("text", "hidden");
}
jQuery("#alertText").val(str);
}
});
然后在你的代码中,而不是jQuery("alert").val()
,你会做jQuery("#alertText").val()
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)