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
}
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
}
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>.
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");