Thursday, May 8, 2008

Busting Javascript alerts

Sometimes it is annoying to see alerts every now and then in web pages. It is not practical to switch off alerts altogether (see this), however it may seem convenient to get control over alerts and do whatever actions: mute, show somewhere else, ...
It is simple like overriding the window.alert function:

window.alert = function(msg)

 // do whatever, for example:
document.title = "busted alert: " + msg
var div = document.getElementById('divid').innerHTML = msg


Of course this is applicable for window.confirm and window.prompt too.

This may appear trivial and useless. However, you can elevate its potential in 2 ways:

First: You can bust alerts of embedded iframes by getting a reference to its content window:

function loaded(iframe) {

 var iframe = document.getElementById('iframeid')
// or iframe = document.frames[0]
// or iframe = document.frames[frame_name]
// or just use the iframe function argument above
iframe.contentWindow.alert = function(msg) {...}


You will have to put previous code in the onload function of the iframe:

<iframe onload="loaded(this)></iframe>

I tried this on both Firefox2 and IE7 and it worked with no problems. Other browsers?

The other way to make this useful is to install Greasemonkey and create a new user script containing the overriding code.
You will have to access the unsafe window object to do so:

unsafeWindow.alert = function(msg){...}

This way you can do anything to alerts coming from any site that will run the user script.

No comments: