有人有在JavaScript中重写alert()函数的经验吗?

哪些浏览器支持这个功能? 哪些浏览器版本支持此功能? 重写函数的危险是什么?


当前回答

我做的一个快速破解来找到警报来自哪里,是去控制台,然后输入这个

function alert(message) { 
  console.info(message);
  debugger;
} 

其他回答

When it comes to js browser functions window.alert is pre-eminent and most well known, people who don't know js know alert() -- rest assured it is supported in all browsers in use today and your code snippet is as well. However, I wouldn't override (well this is more like refactoring rather than override in the OOP sense) alert() for a particular use case as yours because when you actually need to use alert() with no template, and you probably will, then you'll need another non-alert function to do so.

它在firefox和ie8中确实有效。我看不出有什么浏览器是它不能运行的。这是javascript工作的基本原理,尽管人们不经常看到它与原生函数一起使用=)

正如在许多其他答案中所述,您可以使用

window.alert = null

or

window.alert = function(){}

然而,这并不一定会覆盖Window构造函数原型上的函数(注意大写的W),所以黑客仍然可以输入:

Window.prototype.alert.apply(window, ["You were hacked!"]);

因此,你还需要重写该函数:

Window.prototype.alert = null

or

Window.prototype.alert = function(){}

它绝对是“支持的”。这是你的网页,你想做什么就做什么。

我已经这样做了,在不修改库的情况下跟踪分析事件,但通过潜入事件。

使用代理模式:

(function(proxied) {
  window.alert = function() {
    // do something here
    return proxied.apply(this, arguments);
  };
})(window.alert);

如果需要,还可以绕过对原始函数的调用(代理)

更多信息:JQuery类型#代理模式

我做的一个快速破解来找到警报来自哪里,是去控制台,然后输入这个

function alert(message) { 
  console.info(message);
  debugger;
}