Search code examples
javascriptjquerygreasemonkey

How do you close an alert dialog with jQuery?


To me it seems like this would be easy to Google for, but I'm not finding anything. I've searched:

  • jquery click alert
  • jquery submit alert
  • jquery click popup
  • jquery submit popup
  • jQuery click modal dialog
  • jQuery submit modal dialog
  • jQuery click confirmation
  • jQuery submit confirmation

And so on. I fully expect for this to be closed as a duplicate, but I'm listing my searches out so that it can help the next person: maybe it will lead to the answer I couldn't find on my own and save them some time.

That aside, here is the context. I am writing a greasemonkey/tapermonkey userscript that clicks on a button and that button has an event on it that brings up a confirm(). How do I click on the "OK" or "Cancel" button of that confirm popup?


Solution

  • If the site uses window.confirm (regardless of whether it also uses jQuery or not), you can overwrite it and implement your own functionality. For example:

    // userscript code
    window.confirm = () => true;
    
    // site code
    button.addEventListener('click', () => {
      const result = confirm('did you really mean to click the button?');
      console.log(result);
    });
    <button id="button">click</button>

    You cannot use a userscript to interact with any of the window.alert, window.confirm, or window.prompt modals, but

    • such modals are very bad practice, so hopefully you won't see them often anyway
    • all of these methods can be tweaked with a userscript by overwriting them, like in the above snippet, so that the browser modal doesn't come up at all.