alert() not working in Chrome

anonymous coward picture anonymous coward · May 31, 2011 · Viewed 99k times · Source

error

'nuff said. I have absolutely no clue why using alert() there wouldn't work. It works perfectly in Firefox, but gives that error in Chrome.

Answer

Matty F picture Matty F · May 31, 2011
window.alert = null;
alert('test'); // fail
delete window.alert; // true
alert('test'); // win

window is an instance of DOMWindow, and by setting something to window.alert, the correct implementation is being "shadowed", i.e. when accessing alert it is first looking for it on the window object. Usually this is not found, and it then goes up the prototype chain to find the native implementation. However, when manually adding the alert property to window it finds it straight away and does not need to go up the prototype chain. Using delete window.alert you can remove the window own property and again expose the prototype implementation of alert. This may help explain:

window.hasOwnProperty('alert'); // false
window.alert = null;
window.hasOwnProperty('alert'); // true
delete window.alert;
window.hasOwnProperty('alert'); // false