Showing posts with label console. Debugging. Show all posts
Showing posts with label console. Debugging. Show all posts

Saturday, 24 March 2012

Logging and Suppressing JavaScript errors

Logging JavaScript errors to a file by overwriting the window.onerror method

Sometimes you may have intermittent JavaScript errors that you cannot re-produce or maybe you just want to be able to log JavaScript errors for later viewing. Or maybe you just want to suppress them so that end users don't see them.

By using the useful and also dangerous feature of being able to overwrite core JavaScript functions and objects you can utilise this to your advantage by overwriting the window.onerror method.

The window.onerror method takes 3 parameters which are:

  • message : the error message
  • url: the URL of the file that raised the error message
  • line: the line number that the error occurred on.


Therefore it is very easy to create your own window.onerror function to take these values and then make an AJAX call to a server side page which logs the JavaScript error details to a file or database or even sends an email.

Also by overwriting the window.onerror function we can suppress JavaScript errors if we chose to.

Maybe if we are debugging a script and don't want the error console constantly filled up or maybe some of our users are still using Windows 98 and use IE 4.

If we are using unobtrusive JavaScript that builds layer upon layer of functionality starting with the lowest common denominator e.g HTML, then adding JavaScript functionality if they have it, Flash if they have it and so on then we may want to just suppress these JavaScript errors in old browsers.

To suppress a JavaScript error you just need to return true.

This example uses jQuery seeing that is so popular but any AJAX library can be used. The point is that you are taking the error parameters and logging them somewhere useful.

I have used a little JavaScript wrapper object to set some system properties like a config object to define whether error logging is on or off and whether or not to suppress errors in older browsers. 

The code to define which browsers to suppress in can be left to you but I have done a simple test for document.getElementById which means browsers like IE 4 and NN4 won't get errors raised.


// Log JS errors to a file - file is overwritten each day only use when debugging a particular page/site

// Set up our global config options to decide whether to log JavaScript errors and whether or not to suppress them. A simple false/true could suffice but we might want to test for old browsers or certain features. If the browser doesn't support document.getElementById it's a pretty old browser!
GlobalSettings = {
 SystemName : "Strictly-Software",
 Version : 2.0.1,
 LogJSErrors : true,
 SuppressJSErrors : (document.getElementById) ? false : true
}

// override the onerror object
window.onerror = function(msg, url, line)
{   
 // does our global system want to log errors - this could be a Client or Serverside setting
 if (GlobalSettings.LogJSErrors)
 {  
                // using JQuery to post a GET request to a page that logs the error details
  $.get("logJSError.php", { message: msg, errorlocation: url, lineno: line } );
 }
 

 // do we still raise the error or for old browsers which might have a lot of errors do we try and supresss them? Use our global config options again.
 if(GlobalSettings.SuppressJSErrors){  
  // return true to suppress the error so its not raised to the console.
  return true;
 }else{
  // return false to raise the error to the console.
  return false;
 } 
}

Then all you need is to define your server side page logJSError.php (or whatever language you are using) to collect the error data from the request and do whatever you want with it e.g log it somewhere for later viewing.

Remember whilst being able to overwrite functions that already exist is good in certain situations like this and the Lazy Function scenario but it can also cause you severe debugging nightmares like the one I discovered when using the common addEvent naming convention for cross browser adding of events.

Therefore be careful especially when overwriting core JavaScript features but also use them to your advantage when possible.


Tuesday, 21 February 2012

Debugging on the iPhone

Debugging Console on iPhone

I have an iPhone 3GS and one thing I have always found annoying is that when I am developing web pages for display on the iPhone you cannot debug them as easily as you can with a PC.

Yes you can get simulators and use user-agent switchers but they are not the same as debugging on the real device.

If I use an agent switcher and change my user-agent to GoogleBot or IE 6 that isn't got to simulate a web page that tests for agents and devices properly or handle libraries that test for unique iPhone / iPad features available on the device and loaded in by specialist external libraries such as the two finger scroll etc.

A proper coder will test for a BOT in ways that don't rely purely on the user-agent including checking for known BOT IP addresses that the they crawl from, a reverse/forward DNS check or tests for JavaScript or Flash use or all 3 and a myriad of other techniques.

On the iPhone you can easily test whether a user-agent switcher is being used by creating a flash movie and then testing if it's been loaded as we all know iPhone doesn't support flash so a user-agent sniff for "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5" is useless for simulating an iPhone and it's workings properly.

Therefore knowing whether there are JavaScript errors on the page or wishing to output debug messages to the console on an iPhone which you can do easily in all other browsers is a very useful thing to be able to do. I didn't actually find this out until this morning but on the iPhone you can actually do this by going to your settings menu option and enabling it with the following steps.

Go to Settings > Choose the Safari Option > At the bottom of the menu select the Developer option > Enable the "Debug Console" option.

If you then go to any web page you should see at the top of the page will now appear a new panel titled "Debug Console" and if there are no errors on the page it will say "No Errors". If there are errors but no output to the console (e.g with a console.log(msg) function call) then it will list the number of errors and if there are console messages it will tell you the number e.g "7 Logs".

Selecting the console option will show a new screen in which you can view all the console messages. At the bottom of the screen are options to view "All messages", "HTML", "JavaScript" and "CSS". Clicking the relevant tab will show you messages related to those errors.

If there are JavaScript errors it will show you the line number, the error message and a description but unlike a proper browser you cannot click on the error message and view the actual source code.

In fact that is the one bug bear I have about iPhone's Safari browser which is the lack of developer options such as being able to view the source and generated source code as well as controlling options such as white/blacklists for 3rd party cookies, JavaScript and so on. However at least you can view the errors on the device properly if you need to.

Wednesday, 31 August 2011

Would you switch back to IE9 now that they have finally made a good browser?

Now that IE9 is standards compliant and actually good will you switch back to using it?

A few months ago I wrote an article about why I hated debugging in IE8 which revolved around their single threaded event model (window.event) and the delay it took before debug messages were outputted to the console.

A member of the Microsoft team commented that he had run the test case I had created in IE9 and that it had run perfectly. No high CPU, no frozen console, no high memory usage or other performance problems at all.

As you cannot install IE9 on WinXP, which is what I use on my home laptop (due to Vista being shite), I haven't had the pleasure of using Internet Explorer 9 a lot until I installed Windows 7 on my work PC.

I have to say that Windows 7 is actually a great operating system and I especially love the way it has incorporated many of the features of clean up and performance tuning tools like Tune Up Utilities and CCleaner into the main OS.

I also have to say that Internet Explorer 9 is the first IE browser I actually like.

Not only is it blindingly fast they have finally listened to their customers who have been complaining for years and made their JavaScript engine standards compliant.

Obviously this makes the Browser / Document mode spaghetti even harder to detect and I haven't been able to find a way as of yet to detect IE 9 browser mode running as IE 8 or 7 on 32 bit machines but that is not a major issue at all.

What I am wondering though is that now that IE9 is actually a good browser, with a good inbuilt development console and element inspection tools, how many developers will actually return to using it either as their browser of choice for surfing the web or for their primary development.

My browser development survey which I held before IE9 was released showed that developers would rather use Chrome or Firefox for surfing and would also always choose the development tools that those browsers bring than use IE 7 or 8.

I know that I changed from using IE to Firefox as my browser of choice some eons back and I changed from Firefox to Chrome for both surfing (speed is key) and developing (no need for Firebug or any other plugin) the other year when Firefox started to suffer major performance problems.

These performance problems are always either to do with having far too many plugins installed. Setting the browser up to check for new versions and any installed plugins on start up which cause long load times, Firebug issues and errors in the Chrome source. This is on top of all the constant problems that Flash seems to bring to any browser.

I use Chrome for surfing due to it's speed but if I leave a few tabs open all night that contain pages running Flash videos then by morning my CPU has flat-lined and memory has leaked like the Titanic.

This is more a problem with Flash than Chrome and I try to keep this browser for surfing as clean and as fast as possible by not installing plugins. Then if I need to hack around or do some hardcore web development I will use Firefox and all the great plugins when I need to.

I don't think I could really get hacking with Chrome alone as when I am really getting stuck into a site I need my key plugins e.g the web developer toolbar, hackbar, header modifier, Request and Response inspectors e.g HTTP Fox, Firebug, ColorZilla, YSlow and all the Proxy plugins that are available.

However for basic development, piping out messages to the console, inspecting the DOM and checking loaded elements and their responses then Chrome has everything Firebug has without all the JavaScript errors.

In fact it's surprising how many developers don't even realise how much is possible with Chrome's inbuilt developer tools, speed tests, header inspectors, element inspectors and DOM modifiers and other great debugging tools that used to be the preserve of Firebug alone.

Which leads me back to IE9.

Yes it's fast and it's developer tools are okay with options to clear cookies, disable JavaScript, inspect the DOM and view the styles but it's no Chrome or Firebug yet;

Therefore what I want to know is how many people (and by that I mean developers) will switch back to using Internet Explorer 9 for pure web surfing?

For sure it's fast, supports the latest CSS standards and all the great HTML 5 features that we have all seen with floating fish tanks and the like. But is this enough for another browser switch?

I have all the major browsers installed at work on Win7 including IE9, Firefox, Chrome, Opera, Safari, SeaMonkey and a number of others I cannot even remember the names of they are that obscure.

Before upgrading I even had Lynx and Netscape Navigator 4 installed as I used to be so anal that any code such as floating DIV's had to work in the earliest browsers possible. However I only use these browsers for testing and I stick to Chrome (for surfing) and Firefox (for hacking) which leaves little room for IE9 at the moment.

I know it's a good browser. It's standards compliant and it no longer crashes when I try to output anything to the console so why shouldn't I try it again.

Maybe one of my readers can help me decide on the browser of choice for surfing and development and how IE9 fits into that toolset.

Maybe I am missing some really cool features that I would use all the time but to be honest I am not into throwing sheep at randoms or constantly voting sites up and down and writing comments on them. Therefore for me to switch back from Chrome to another browser such as IE9 there has to be a really good reason for me to do so.

So does anyone have any reason why I should re-consider using IE9 at work for my web surfing or development?

Sunday, 23 January 2011

Why I hate debugging in Internet Explorer 8

Debugging Javascript in Internet Explorer

Now with IE 8 and it's new developer toolbar debugging Javascript should have become a lot easier. There is now no need to load up Firebug Lite to get a console or use bookmarklets to inspect the DOM or view the generated source and in theory this is all well and good.

However in practise I have found IE 8 to be so unusable that I have literally stopped using it during development unless I really have to.

When I do find myself having to test some code to ensure it works in IE I have to make a little prayer to the God of Geekdom before opening it up because I know that within the next 5 minutes I will have found myself killing the IE process within Task Manager a couple of times at the very least.

Not only does IE 8 consume a large portion of all my CPU cycles it's very ill thought out event model makes debugging any kind of DOM manipulation a very slow painful chore.

Unlike proper browsers IE's event model is single threaded which means that only one event can occur at any point in time during a pages lifetime. This is why IE has the window.event object as it holds the current event being processed at any point in time.

Many developers over the years have moaned at IE for this and have hoped that with each new release of an IE browser that they would fix this odd behaviour. However every time a new version is rolled out a lot of web developers are always bitterly disappointed because apparently Microsoft feels this quirky event model is a design feature to be enjoyed rather than a bug to be suffered and they don't seem to have any intention whatsoever of fixing it or making it DOM 2 compliant at the least.

I don't know why they cannot do what Opera does and just implement both event models. At least that way they can make all the proper web developers happy at the same time as all the sado masochists who enjoy IE development

This event model really comes into its own when you are trying to debug something using the new developer toolbar as very often you want to pipe debug messages to the console.

If you are just outputting the odd message whenever a button is clicked or form loaded then this can be okay but if you attempt to do anything that involves fast moving events such as moving elements around the page or tracking fast incrementing counters then you will soon suffer the pain that comes with waiting many minutes for the console to catch up with the browsers action.

Whereas other browsers such as Chrome or Firefox are perfectly capable of outputting lots of debug messages to the console at the same time as mousemove events are being fired IE seems to either batch them all up and spit them out when the CPU drops below 50% (which might be never) or occasionally the whole browser will just crash.

At first I thought it was just me as my work PC is not the fastest machine in the office but I have seen this problem on many other peoples computers and I have also experienced it at home on my Sony VAIO laptop.

As a test I have created the following page which can be found here:


Try it out for yourself in a couple of browsers including IE 8 and see what you think. I haven't had the chance to test IE 9 yet so I don't know if the problem is the same with that version but I would be interested to know if anyone could test this for me.

The test is simple and just includes a mousemove event which collects the current mouse co-ordinates and pipes them to the console. It does this for a number of iterations which can be set with the input box.

I have found that IE will manage when setting this counter to anything less than 100 but putting it to 1000 or above it just crashes or freezes my own browser as well as killing the CPU.

Let me know what you think of this test and whether anyone else has major issues with IE and it's console logging capabilities.