Clicking 'OK' on alert or confirm dialog through jquery/javascript?

18,799

Solution 1

As far as I know if you use a standard alert() call you cannot trigger an "OK" click because the alert call blocks the normal JS event loop.

However you should be able to replace window.alert and window.confirm with your own function that does nothing:

window.alert = function() {
    console.log.apply(console, arguments);
};

Place these at the top of your JS before anything else is loaded and any subsequent calls to alert() or confirm() will call these instead.

Solution 2

You want something like:

<script type="text/javascript">
var oldConfirm = confirm;
var oldAlert = alert;

confirm = function() {
    return true;
};
alert = function() {
    return true;
}

var response = confirm("Is this OK?");

if (response) {
    alert("Yay");
}
else {
    alert("Boo");
}

confirm = oldConfirm;
alert = oldAlert;
</script>
Share:
18,799

Related videos on Youtube

PhD
Author by

PhD

Updated on June 04, 2022

Comments

  • PhD
    PhD about 2 years

    I was thinking of writing some UI tests in backbone.js and jquery. They may not be the best way to do it but it's something that I was thinking about - to automate the tests without record and playback - through plain code.

    The only thing that made me scratch my head using this approach is this: In some 'use-case flow' (of the execution) confirm/alert dialogs would show up. I'd like to click 'Ok' and continue the flow - is this even doable through plain javascript code? How?

    Note: I do know GUI testing libraries exist, but I want to know how to do it using just jQuery/javascript code, if at all possible.

    • joshin4colours
      joshin4colours
      +1 for trying a different approach to UI testing
  • PhD
    PhD over 12 years
    I'm not sure how it would help...could you augment the 'intent' with some explanation please? :)
  • SubParProgrammer
    SubParProgrammer over 12 years
    Yes, sorry. window.confirm and confirm refer to the same thing.
  • PhD
    PhD over 12 years
    I understood the intent of your code after alnitak clarified a few things :)