Mystery JS Alert

Posted on Jun 30, 2015

One of my fellow developers at work recently started complaining that he was getting an alert showing up on his page on a development system. Obviously this raised our XSS-aware eyebrows and investigations soon started.

Thanks to the way JQuery subsumes event handlers it can sometimes be very tricky to find out what exactly was triggering the alert, and without finding out what triggers the alert you can’t find the problem and fix it. Alerts can also be hard to get a debugger to breakpoint on, if at all possible.

This little snippet helped my colleague as they could bake it in the top of every page served out to override the alert function and then check their console to see the full stack of calls that resulted in the call to alert(). It could also be modified to call an AJAX endpoint posting the data back so that users who might not have the console object in their browser can still be diagnosed simply.

//Rename the alert function to alert_ so it can still be used
window.alert_ = window.alert;

//Override the regular alert function with one that
//  console.log's the stack to find out what called it
window.alert = function() {
    e = new Error();
    console.log(window, arguments, e.stack);
    alert_.apply(window, arguments)
};

I also modified this snippet for one of our testers who uses Selenium and wanted to use JavaScript in his Selenium test to parse a reference number from an alert on one page to use throughout the rest of his test case. In that case we overrode the alert method in the same way, had a regex inside to parse out the reference he needed and wrote that to a new hidden span in the page which his selenium script could then find and get the value from to store and use.