How to find out where the alert is raised from?

18,146

Solution 1

You can overwrite alert, and create an Error for the stack trace:

var old = alert;

alert = function() {
  console.log(new Error().stack);
  old.apply(window, arguments);
};

Solution 2

You can monkeypatch the alert to do so:

//put this at the very top of your page:
window.alert = function() { throw("alert called") }

Solution 3

How about wrapping the alert?

window.original_alert = alert;
alert = function (text) {
    // check the stack trace here
    do_some_debugging_or_whatever();

    // call the original function
    original_alert(text);
}

This should be cross-browser.

Solution 4

There is a trace function is console is provided by all major browsers. console.trace();

With Proxy approach, as described in earlier answers, and console.trace(), we can print the entire stack with line number in console itself.

(function(proxied) {
  window.alert = function() {
	console.trace();
    return proxied.apply(this, arguments);
  };
})(window.alert);

This is an IIFE. Every alert call will have its trace printed in the console.

Share:
18,146
Mo Valipour
Author by

Mo Valipour

Software Engineer. I blog at http://mvalipour.github.io/

Updated on June 15, 2022

Comments

  • Mo Valipour
    Mo Valipour almost 2 years

    I'm just curious to know
    Is there ANY ways in ANY browser to find out where the alert I get is raised from?

    I tried it in chrome but there is no call stack available when alert shows.

    Any idea?