有人有在JavaScript中重写alert()函数的经验吗?
哪些浏览器支持这个功能? 哪些浏览器版本支持此功能? 重写函数的危险是什么?
有人有在JavaScript中重写alert()函数的经验吗?
哪些浏览器支持这个功能? 哪些浏览器版本支持此功能? 重写函数的危险是什么?
当前回答
超铃报警功能无危险。每个浏览器都支持它。
例如:
// function over riding. Redirecting to Console with Firebug installed.
function alert(message) {
console.info(message);
}
alert('This is an override.');
其他回答
现代浏览器中的所有JavaScript实现都支持重写。
危险很简单,如果您重写了诸如alert()这样的常见函数,就会把其他团队成员逼疯。
所以除非你重写函数作为调试或修改现有代码的工具,否则我认为没有任何理由这样做。只需要创建一个新函数。
我遇到过一个要求,即在显示实际警报消息的同时显示默认消息。这就是我如何做到的。
const actualAlertFunc = window.alert;
window.alert = function(msg) {
actualAlertFunc('some default message '+ msg);
}
我已经在chrome上测试过了。 我不确定这是否是一种好的做法,但它达到了目的。
我认为每个Javascript实现都将支持这一点,并且这样做不会有任何危险。通常用HTML/CSS代替简单的os风格的警告框。这样做意味着您不必更改现有的代码!这一事实使得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(){}
Ladislav。 对于IE8,你可以像这样重新定义alert()
/**
* Definition of global attached to window properties <br/>
*/
(function() {
nalert = window.alert;
Type = {
native: 'native',
custom: 'custom'
};
})();
/**
* Factory method for calling alert().
* It will be call a native alert() or a custom redefined alert() by a Type param.
* This defeinition need for IE
*/
(function(proxy) {
proxy.alert = function () {
var message = (!arguments[0]) ? 'null': arguments[0];
var type = (!arguments[1]) ? '': arguments[1];
if(type && type == 'native') {
nalert(message);
}
else {
document.write('<h1>I am redefiend alert()<br/>Alert say: '+message+'</h1>');
}
};
})(this);
并调用as
alert('Hello, hacker!');
nalert('I am native alert');
alert('Hello, user!', Type.custom);