Phantom.js-在警报框中获取文本 [英] Phantom.js - Get Text Inside Alert Box
问题描述
是否可以使用Phantom.js在警报框中获取文本?
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!");
});
});
推荐答案
无法以这种方式从alert
获取消息(没有名为<alert>
的HTML元素,这就是您要尝试的内容.查找使用jQuery).但是,您可以做的是重新定义window.alert
来执行其他操作,例如登录到控制台.然后,您可以使用onConsoleMessage
查看控制台消息.为了将其与可能获得的其他控制台消息区分开,可以为其指定一个唯一的前缀.在这种情况下,我使用了ALERT:
:
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 redefine window.alert
to do something else like log to the console. Then you can use onConsoleMessage
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 used ALERT:
in this case:
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
中),然后简单地查询该值:
If you don't want to go the onConsoleMessage
route, you could create your own hidden input
element (in the redefined alert
) and then simply query that value:
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("#alertText").val()
,而不是jQuery("alert").val()
.
Then in your code, instead of jQuery("alert").val()
, you would do jQuery("#alertText").val()
.
这篇关于Phantom.js-在警报框中获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!