我正在开发一个项目并注意到其中一位核心开发人员在他的JS中覆盖了alert()
方法。
是否可以在不询问/更改其代码的情况下恢复它?
他做了类似的事情。
function alert() {
// his code
}
答案 0 :(得分:4)
You can make an intermediate <iframe>
.
var f = document.createElement("iframe");
f.width = 0;
f.height = 0;
f.src = "about:blank";
f.onload = function() {
f.contentWindow.alert("Hi!");
document.body.removeChild(f);
};
document.body.appendChild(f);
不要制作中级<iframe>
。
答案 1 :(得分:2)
如果您可以在导致此问题的代码之前注入代码,则可以“修复”它:
E.g。
window._alert = window.alert;
// bad code ..
window.alert = function() {};
// restore correct function
window.alert = window._alert;
当然,这意味着其他代码现在可能无法正常运行或导致不需要的警告框。
它还取决于其他代码覆盖alert
的准确程度。如果只是草率的代码,其中一个名为alert
的函数被错误地提升到全局范围,你可以通过将整个代码块包装在一个匿名函数中来修复它:
(function() {
// scope to this block
var alert;
// bad code here
alert = function() {};
})();
// alert doesn't pollute global scope:
alert("HI");