WolfPRD
WolfPRD

Reputation: 11

Selenium + Perl: Check if alert exists?

Selenium 2.* is running on Linux with Firefox as the browser.

I am using perl with the Selenium::Remote::Driver module to interact with the server.

Is there anything available to check if an alert is present? The perl module provides several functions to click OK on an alert, or to get the text from it, but this will raise an error if there is no alert - how to avoid an error and still get rid of any alert?

Basically, I want to remove all alerts when a page finished loading (if any), but not sure how?

Another option that I tried is disabling all alerts by setting a variable in the firefox profile (which works when you use the browser yourself), but somehow the alert is still there when the browser is used by Selenium because i think Selenium handles the alert itself because of the "handlesAlerts" capability, which is always set to true, and I'm not sure how to disable it. It may be the solution if it's not possible to check for the existence of an alert.

Anyone have an idea?

Upvotes: 1

Views: 878

Answers (2)

Judy Morgan Loomis
Judy Morgan Loomis

Reputation: 91

I created a couple of functions that check for an alert and then either cancel or interact with it as needed.

use Try::Tiny qw( try catch );

# checks if there is a javascript alert/confirm/input on the screen
sub alert_is_present
{
    my $d = shift;
    my $alertPresent = 0;
    try{
        my $alertTxt = $d->get_alert_text();

        logIt( "alert open: $alertTxt", 'DEBUG' ) if $alertTxt;
        $alertPresent++;

    }catch{
        my $err = $_;
        if( $err =~ 'modal dialog when one was not open' ){
            logIt( 'no alert open', 'DEBUG2' );
        }else{
            logIt( "ERROR: getting alert_text: $_", 'ERROR' );
        }
    };

    return $alertPresent;
}

# Assumes caller confirmed an alert is present!! Either cancels the alert or
  types any passed in data and accepts it.
sub handle_alert
{
    my ( $d, $action, $data ) = @_;

    logIt( "handle_alert called with: $action, $data", 'DEBUG' );

    if( $action eq 'CANCEL' ){
        $d->dismiss_alert();
    }else{
        $d->send_keys_to_alert( $data )
            if $data;
        $d->accept_alert();
    }

    $d->pause( 500 );
}

Upvotes: 1

user1126070
user1126070

Reputation: 5069

You could try to dismiss alerts, use eval block to handle exceptions

eval {
   $driver->accept_alert;
};
if ($@){
 warn "Maybe no alert?":
 warn $@;
}

Upvotes: 2

Related Questions