Server-logging client-side javascript errors
There are several examples of this already on the net, but this technique came in handy on a recent site I programmed. The concept is that you overwrite any existing browser reaction to the window.onerror event with your own function that sends an XMLHttpRequest containing gathered error information to a server-side script which logs that information to a file or database.
The user-experience as defined by the designer & client called for virtually every page to have a “dashboard” feel, whereby a site visitor could click buttons & links and the main content area of the page would be replaced (typically via innerHTML.)
Cross-browser debugging nearly became a serious issue; it was like a wild shoot-out in a digital saloon, with AJAX bullets flying through HTML-tag-cowboy hats and ricocheting off the piano player’s include files.
I got pretty much everything straightened out, but we still had the rare non-responsive button or empty content screen. So as we opened the site to a private beta, the following bit of PHP helped the browsers with issues call attention to themselves.
echo "<script>
window.onerror = function(msg, err_url, line){
var params = 'jserror=1&msg=' +msg+ '&url=' +err_url+ '&line=' +line+ '&ua={$_SERVER['HTTP_USER_AGENT']}';
whateverAjaxCallYouUse('action.php?'+params);
</script>";
With the increasing reliability of document.activeElement you could conceivably get more detailed information about the page element which caused the problem, however in my case I was only interested in the error messages themselves. In the untested example below, I create a string of JSON text from the activeElement‘s attributes.
var curr = (document.activeElement) ? document.activeElement : false;
if(curr){
var json_string = '{' +
' "element" : "' + curr +
' ","tagname" : "' + curr.tagName +
' ","name" : "' + curr.name +
' ","id" : "' + curr.id +
' ","parent" : "' + curr.parentNode +
' ","href" : "' + curr.href +
' ","src" : "' + curr.src +
' ","onclick" : "' + curr.onclick +
' ","onfocus" : "' + curr.onfocus +
' ","onblur" : "' + curr.onblur + '"}';
}
Or something to that effect, there’s probably a smarter way to do it.
Obviously, this suppresses any normal error reporting in the browser so you’ll want a way to deactivate this behavior for when you’re debugging as you won’t see any errors yourself. In my case, since the site was decently MVC’d it was easy to not echo this function based on whether the appropriate administrator variables were set in the $_SESSION array.
Tags: ajax, bug, errors, javascript, log