javascript 如何找出警报是从哪里发出的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7808665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find out where the alert is raised from?
提问by Mo Valipour
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.
我在 chrome 中尝试过,但是在显示警报时没有可用的调用堆栈。
Any idea?
任何的想法?
回答by pimvdb
You can overwrite alert
, and create an Error
for the stack trace:
您可以覆盖alert
,并Error
为堆栈跟踪创建一个:
var old = alert;
alert = function() {
console.log(new Error().stack);
old.apply(window, arguments);
};
回答by Herberth Amaral
You can monkeypatch the alert to do so:
您可以对警报进行猴子补丁来执行此操作:
//put this at the very top of your page:
window.alert = function() { throw("alert called") }
回答by Piskvor left the building
How about wrapping the alert
?
包裹起来怎么样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.
这应该是跨浏览器的。
回答by Aswin
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.
使用代理方法(如前面的答案中所述)和 console.trace(),我们可以在控制台本身中打印带有行号的整个堆栈。
(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.
这是一个 IIFE。每个警报调用都会在控制台中打印其跟踪。