0

I'm working on a project and noticed that one of the core developers overwrote alert() method in his JS.

Is it possible to recover it without asking/changing his code?

He did something like..

function alert() {
   // his code
}
Moon
  • 22,195
  • 68
  • 188
  • 269
  • How did he overwrite it? – Ry- Sep 26 '13 at 00:26
  • function alert() { // his own code here } – Moon Sep 26 '13 at 00:26
  • Are you using revision control? I guess I don't understand the question if not. Are you asking how you can un-save a file? – Mike Brant Sep 26 '13 at 00:27
  • And your code has to come after that code? – Ry- Sep 26 '13 at 00:27
  • @MikeBrant // yes, and I can simply remove his code. I just don't want to touch a core code. – Moon Sep 26 '13 at 00:29
  • 4
    Whapping the developer with a newspaper would be the best option. The correct solution that won't break current code that depends on the redefinition would be saving the old `alert()` **before** clobbering it under a different name (like `_alert()`) then using that. – millimoose Sep 26 '13 at 00:29
  • @minitech // yes, it should go after his code. – Moon Sep 26 '13 at 00:29
  • That said, why use the native alert() in the first place? `console.log` or a DHTML dialog is almost always nicer. – millimoose Sep 26 '13 at 00:29
  • @millimoose // I don't want any fancy DHTMl dialog. I just want to use the native one. – Moon Sep 26 '13 at 00:40

2 Answers2

6

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);

Don’t make an intermediate <iframe>.

Ry-
  • 218,210
  • 55
  • 464
  • 476
2

If you can inject code before the code that's causing this problem, you can "fix" it:

E.g.

window._alert = window.alert;
// bad code ..
window.alert = function() {};
// restore correct function
window.alert = window._alert;

Of course, that means that the other code might now function incorrectly or cause unwanted alert boxes.

It also depends on how exactly the other code is overwriting alert. If it's just sloppy code where a function called alert is being hoisted to the global scope by mistake, you potentially fix it by wrapping the whole codeblock in an anonymous function:

(function() {
    // scope to this block
    var alert;

    // bad code here
    alert = function() {};
})();
// alert doesn't pollute global scope:
alert("HI");
Hamish
  • 22,860
  • 8
  • 53
  • 67