Tuesday, February 12, 2008

Catching JavaScript errors and masking over the alert() method

OK, I didn't think this would be such an amazing concept, but apparently someone did.  JavaScript actually allows you to override the default alert() behaviour; you can use this to display a fancy dialog in place of the standard modal alerts, or just alter the alert:

<script type="text/javascript">
// <![CDATA[
   var originalAlert = window.alert;

   window.alert = function(msg) {
      originalAlert('Altered Message: ' + msg);
// ]]>

Furthermore, you can apply the same principal to override the error behaviour:

window.onerror = function() {
   alert('An error occured');

The result of an error on the page is a popup "Altered Message: An error occurred".

You can test this out by adding another function and method

function throwError(e) {
    throw 'Exception';

<input type="button" value="Click Me" onclick="throwError();" />

No comments: