0

I'm trying to understand if there is a way to detect those.

I'm writing a js bot that navigates through a list of websites and perform different actions. I'm not quiete sure how this project will end nor where it leads but I'm learning a lot. It happens some of the websites send me an 'alert' popup, which freezes my browser and my bot by extension until I refresh the page manually.

It might sound like a dumb question but I've looked for hours and most stuff I could find was about selenium, or for back-end webmasters, to check if the alert is showing correctly on client-side.

I tried some window.addEventListener(alert, myFunction() { ... }) but it doesn't work at all. There is just too much informations and google isn't helping me at all to find the right answer.

Hopefully someone could share the code of a isAlertPresent() - like function. I don't need it to click on OK, just to know if an alert is present at a precise time.

Thank you all!

Dmitry S.
  • 1,544
  • 2
  • 13
  • 22
  • There is no way to do this. Once an alert is popped, the JavaScript on that page stops running until it has been dismissed. See the answer here: https://stackoverflow.com/a/563905/7890967 – Jacob Penney Mar 11 '21 at 19:36

1 Answers1

0

You can override window.alert method like this:

window.actualAlert = window.alert;
window.alert = function(message) {
  console.log("Alert popup opened");
  // ...custom logic here
  window.actualAlert(message);
}
ranjan_purbey
  • 421
  • 4
  • 11
  • Thanks a lot, it's exactly what I needed. I was thinking in a bad spirit : – coffeelover Mar 11 '21 at 20:54
  • It's working like a charm in the web console, but I can't manage to make it act the same way on my bot. Because I don't need to keep the original window.alert, I shorted your lines to `window.alert = function(message) { console.log("Alert popup opened"); setTimeout(function(){ AutoSwitch(); }, 5000); }` But it keeps showing up original alert, instead of calling AutoSwitch(). Console doesn't show "Alert popup opened" either at that point. My window.alert definition basically overrides website's original one, what am I missing? – coffeelover Mar 12 '21 at 16:50
  • Seems like the target website is calling `alert` before your code runs. Make sure you insert this code in the `` section of the website before any script tags. – ranjan_purbey Mar 12 '21 at 19:08
  • Yes, that was my conclusion too. However when I paste the exact same line in the webconsole, once page is loaded, then manually trigger an alert on the page, it works as expected. My code is inserted through Violentmonkey browser extension, which is an alternative to Greasemonkey or Tampermonkey. I found few minutes ago I could use the `@grant unsafeWindow` property and override the function that way. I believe there must be a better solution.. – coffeelover Mar 12 '21 at 20:33