0

I want to create a js code snippet which will run onclick of a button on page. After clicking that button it will find whether the console has some errors? (i.e. if its showing some error in status bar in IE) If it has error then it will show an alert box saying that some js code failed on this page. Otherwise will show msg "Passed"

Is it possible to get list of js errors from within the page?

coure2011
  • 40,286
  • 83
  • 216
  • 349
  • 1
    Here's a similar issue you may find help in:- http://stackoverflow.com/questions/6970475/get-all-javascript-errors-on-page-javascript-error-handling – BenhurCD Feb 06 '13 at 07:56
  • Man these guys are on it. Good work NullPointer, Vicky, Thor, Fraser and let's not forget RB. Truly great work on finding that duplicate. I hope you as happy with it as I am appreciative of your valiant efforts. Amazing work guys. Amazingly Brilliant I might add. Wow. Just wow. – King Friday Feb 07 '13 at 07:36

3 Answers3

0

You could use the 'try' and 'catch' directives

try
    {
    // code that may have an error
    }
catch(e)
    {
    alert('There was an error: '+e.message);
    }
finally
    {
    alert('Execute this bit anyway');
    }
Rembunator
  • 1,305
  • 7
  • 13
0

As far as I know, it is not possible to read the console output. You can, however, assign a handler to window.onerror to capture all JavaScript errors, that occur inside a page.

Note that this is not implemented in all browsers. I can't find a compatibility table for it right now, though.

Sirko
  • 72,589
  • 19
  • 149
  • 183
0
<button id="button">Bug out</button>
<script>
var myErrors = [],
startTrackingErrors = false;

window.onerror = function (errorMessage, url, lineNumber) {
    if (!startTrackingErrors) { return false; }
    myErrors.push({
      errorMessage : errorMessage,
      url : url,
      lineNumber : lineNumber
    });
    return true;
};

document.getElementById('button').click = function() {
    startTrackingErrors = true;
    // put your buggy code here

    // loop through "myErrors" array when done
};
</script>
King Friday
  • 25,132
  • 12
  • 90
  • 84