14

My script clicks an image on a site. The image has an anchor href and an onclick href, but the onclick href has a confirm box that pops up once it's clicked.
The onclick HTML is:

onClick="this.href='link2';if (!confirm('Are you sure?')) { return false; }

How do I get the script to click OK in that confirm box, once it pops up?

I'm using this function to click the picture link:

function click(elm) {
 var evt = document.createEvent('MouseEvents');
 evt.initMouseEvent('click', true, true, window, 0, 1, 1, 1, 1, false, false, false, false, 0, null);
 elm.dispatchEvent(evt);
}
click(picture element)
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Frozsht
  • 305
  • 1
  • 3
  • 8

1 Answers1

31

You can override the confirm method to temporarily silence it and return true. Below example will silence a confirm dialog only once, and only if it's called. Once the silenced dialog is executed, it will restore its original functionality and subsequent call to confirm method will work as normal.

var realConfirm=window.confirm;
window.confirm=function(){
  window.confirm=realConfirm;
  return true;
};
click(picture element);
Jay
  • 4,627
  • 1
  • 21
  • 30
  • Works like a charm. You saved lots of my effort. I didn't think that it can be override... – Irfan Raza Jun 28 '16 at 13:27
  • Did you add these two lines `var realConfirm=window.confirm;` and `window.confirm=realConfirm;` to make it only dismiss one alert/confirm notification? Because just returning true to the alert works fine and kills all future alerts: `alert = function () { return true; }` Or even a one liner like this `alert = true;` Although the one liner gives an error `Uncaught TypeError: alert is not a function` @Jay – Shayan Sep 04 '19 at 13:19