Phantom.js - Get Text Inside Alert Box

。_饼干妹妹 提交于 2019-12-20 04:09:50

问题


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!");
  });
});

回答1:


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
    }
});

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);
    }
});

Then in your code, instead of jQuery("alert").val(), you would do jQuery("#alertText").val().



来源:https://stackoverflow.com/questions/19822812/phantom-js-get-text-inside-alert-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!