cll*_*pse 206 javascript overriding
有没有人有过覆盖alert()JavaScript函数的经验?
Mik*_*ier 209
它绝对是"支持"的.这是您的网页,您可以随心所欲地做任何事情.
我已经这样做了,无需修改库就可以跟踪分析事件,但可以潜入事件.
使用代理模式:
(function(proxied) {
window.alert = function() {
// do something here
return proxied.apply(this, arguments);
};
})(window.alert);
Run Code Online (Sandbox Code Playgroud)
如果需要(代理),您也可以绕过对原始功能的调用
更多信息:JQuery Types #Proxy Pattern
Pab*_*era 23
虽然大多数浏览器都支持覆盖它,但要小心你正在做的事情.
由于默认警报框阻止执行线程,因此依赖此行为的某些库可能不再起作用(充其量).
你应该是一个好公民,避免接触原生API.如果你这样做,你可以在使用第三方代码时解决问题.
但是,如果要在特定上下文中重新定义警报行为,可以使用匿名函数将其括起来,如下所示:
/* new funky alert */
function myFunkyAlert(msg) {
/* here goes your funky alert implementation */
alert("Look ma!\n" + msg);
}
(function(alert) { // anonymous function redefining the "alert"
/* sample code */
alert("Hello World!");
})(myFunkyAlert);
Run Code Online (Sandbox Code Playgroud)
use*_*820 15
Overring警报功能没有危险.每个浏览器都支持它.
例如:
// function over riding. Redirecting to Console with Firebug installed.
function alert(message) {
console.info(message);
}
alert('This is an override.');
Run Code Online (Sandbox Code Playgroud)
Jos*_*ola 13
我认为每个Javascript实现都会支持这一点,并且没有任何危险.通常用普通的OS风格的警报框替换为HTML/CSS更优雅的东西.这样做意味着您不必更改现有代码!可以使Javascript变得非常棒的事实.
Jac*_*ack 12
正如许多其他答案所述,你可以用它来覆盖函数
window.alert = null
Run Code Online (Sandbox Code Playgroud)
要么
window.alert = function(){}
Run Code Online (Sandbox Code Playgroud)
但是,这并不一定会覆盖Window构造函数原型上的函数(注意大写W),所以黑客仍然可以键入:
Window.prototype.alert.apply(window, ["You were hacked!"]);
Run Code Online (Sandbox Code Playgroud)
因此,您还需要使用以下方法覆盖该函数:
Window.prototype.alert = null
Run Code Online (Sandbox Code Playgroud)
要么
Window.prototype.alert = function(){}
Run Code Online (Sandbox Code Playgroud)
小智 6
拉吉斯拉夫.
对于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);
Run Code Online (Sandbox Code Playgroud)
并打电话给
alert('Hello, hacker!');
nalert('I am native alert');
alert('Hello, user!', Type.custom);
Run Code Online (Sandbox Code Playgroud)