symbol heatxsink.com blog  ·  archive  ·  about  ·  Feed feed

Surpressing the Ugly Javascript Alert

Tuesday, May 12, 2009 12:51 AM

Ever work in an environment where developers use javascript:alert("oh hai!"); to debug their code? The lack of using console.log now results in nasty javascript alerts all over the place in production code. It is a less than plesant user experience. The real way to solve this problem is to scrub the source code of all javascript alerts. Anyhow I wrote some javascript to surpress window.top.alert.

This script block should be thrown somewhere in the head, and slingshot.load() in the onload/onready event. For purposes of my example I just threw the slingshot.load() right inline.

<script type="text/javascript">
    var slingshot = {
        load:function(){
            window.top.oldAlert = window.top.alert;
            window.top.alert = function(){ return; };
        },
        trace:function(message){
            if(slingshot.debug)
            {
                window.top.oldAlert(message);
            }
        },
        debug:false
    };
    slingshot.load();
</script>

In order to actually show the alerts just set slingshot.debug to true.

<script type="text/javascript">
    slingshot.debug = true;
    slingshot.trace("hello world!");
</script>

Enjoy.