Phantom.js - Get Text Inside Alert Box

2019-03-03 07:30发布

问题:

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().