Search code examples
javascriptautomationalertcasperjsheadless

Wait for a web page alert in CasperJS


I'm a newcomer to CasperJS and after a couple hours I can login and navigate a few webpages with it, but I'm stumped by the alert message on this website: https://www.macysliquidation.com/

I need to get rid of the alert so I can login.

My simple (non-working) code is:

var casper = require('casper').create();
casper.userAgent('Mozilla/12.0 (compatible; MSIE 6.0; Windows NT 5.1)');

casper.on('remote.alert', function(message) {
    this.echo('alert message: ' + message);
    // how do i get rid of the popup??
    this.thenClick();
});

casper.start('https://www.macysliquidation.com/');


casper.then(function() {
    // login here
    this.sendKeys('#txtUsername','username');
    this.sendKeys('#txtPassword','password');
    this.thenClick('#btnLogin');
 });

casper.run(function() {
    // see what went on
    this.capture('page.png');
    this.echo('done').exit();
});

Till the time the alert is clicked away, the login controls aren't visible/available. So the above js returns

Cannot get informations from #txtUsername: element not found


Solution

  • As you already noticed the function capser.waitForAlert() is available since version 1.1-beta4. You can copy the function from the code if you don't have the time to upgrade:

    casper.waitForAlert = function(then, onTimeout, timeout) {
        ...
    };
    

    Problem:

    Alerts and confirm just happen and they don't stop the execution in PhantomJS and CasperJS. They are also not part of the page and cannot be clicked on.

    If you would register to the error events (resource.error and page.error and remote.message is always a good idea) in CasperJS, you would have seen that a specific resource error was thrown:

    {"errorCode":6,"errorString":"SSL handshake failed","id":1,"url":"https://www.macysliquidation.com/"}
    

    If you would have checked the status of the page, you would have seen that it wasn't loaded.

    Solution:

    Run CasperJS with --ignore-ssl-errors=true and depending on your PhantomJS version with --ssl-protocol=tlsv1. More information here.