Question

i have this function which find button and click it, but after that alert appears and i need to confirm it using phantom.js

function() {
  page.evaluate(function() {
    $('.item-list clicked').first().find($('.comment-delete')).find('a').click();
  })
}

may be i can emulate function which call alert whithout click immediately ? or use function waitFor for waiting this alert?(unlikely this, waitFor waiting only for DOM objects i think so)

Was it helpful?

Solution 2

As far as I know, Phantom.JS is headless. The only thing you can do is get the context of the alert with

window.onAlert = function(alertText){
    ...
   }

but no more than this I think. You cannot either close (in general) or render (in Phantom.JS) the alert programmatically.

Some sources:
* Render JavaScript alerts with Phantom.JS
* Close alert programmatically

OTHER TIPS

I can't find the other stackoverflow answer that helped me answer this as well but basically you can inject a javascript function that will confirm the alert popup:

Here's my python webdriver implementation:

def example_js_confirmation( self ):
    js_confirm = 'window.confirm = function(){return true;}'    # .js function to confirm a popup
    self.execute_javascript( js_confirm )
    self.find_by_id( 'submit' ).click()
    self.execute_javascript( 'return window.confirm' )  # trigger the injected js that returns true (virtually click OK)

It's on somebody's todo list =) : Selenium Desired Capabilities - set handlesAlerts for PhantomJS driver

"Confirm an alert" is a confusing phrase, because Javascript provides both alert (which shows a message with an OK button) and confirm (which shows OK and Cancel buttons), and it's not clear which one you mean.

At least PhantomJS 2.x behaves as if it clicks OK on alert boxes and Cancel on confirm boxes.

If you want to click OK instead of Cancel on confirm boxes, you could call execute_javascript to override window.confirm to return true as long as you're not worried about confirm boxes that pop up during the load process which will be dealt with before your execute_javascript has a chance to intervene. If you want to catch those as well, the best thing I can think of is to patch PhantomJS source or inject the JS via an upstream proxy.

I did that:

// 1) override window.alert
page.evaluate(function(){
  window.alert = function(msg){
    window.callPhantom({alert: msg}); // will call page.onCallback()
    return true; // will "close the alert"
  };
});

// 2) re-bind to onAlert()
page.onCallback = function(obj) {
  page.onAlert(obj.alert); // will trigger page.onAlert()
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top