如何找出警报的来源?

Mo *_*our 49 html javascript browser firefox google-chrome

我只是很想知道
在任何浏览器中是否有任何方法可以找出我得到的警报从哪里来?

我在chrome中尝试了它,但是当警报显示时没有可用的调用堆栈.

任何的想法?

pim*_*vdb 104

您可以覆盖alertError为堆栈跟踪创建一个:

var old = alert;

alert = function() {
  console.log(new Error().stack);
  old.apply(window, arguments);
};
Run Code Online (Sandbox Code Playgroud)

  • 这是我见过的最巧妙的技巧之一。如果可以的话,我会给这个“StackOverflow gold”(比如 reddit gold)。万分感谢。 (2认同)

Her*_*ral 7

您可以对警报进行猴子补丁来执行此操作:

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


Pis*_*3.0 5

包裹起来怎么样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);
}
Run Code Online (Sandbox Code Playgroud)

这应该是跨浏览器的。