Posts Tagged ‘Debug’

F12 The best kept web debugging secret

Secret2Shhh don’t tell anyone about this blog, then you will look brilliant in front of your co-workers when you show them these cool tools! Have you found the F12 key yet in Internet Explorer? I will admit that until 6 months ago I hadn’t. If you are running Internet Explorer 8 or 9 you can try it right now. Just hit the F12 key and a window appears at the bottom of your screen. This window will help you debug your web pages! No external tools or plug-ins required! The developer tools were available in IE8, but there were some new features added in IE9, so if you haven’t done so yet, download IE9 so you get the every last bit (and byte!)

The developer tools give you six different tabs to help you debug and walk through the code on your web site.

Tab

Description

HTML Your tab for checking out the HTML on the web page with the options you would expect, for clearing the cache and refreshing the page.
CSS This tab allows you to examine each of the CSS files used to style your page. You can even deselect different CSS style settings to see how it affects the appearance of the page.
Console This tab lets you receive error messages from internet explorer and send your own messages back from your code without changing the execution flow of your code. Console reminds me of the output window and the debug object in the Visual Studio. I wrote a blog talking about how to use the Console object to display messages.
Script This tab allows you to quickly debug JScript complete with breakpoints and variable watches.
Profiler This tab has a script profiler that allows you to analyze the performance of JavaScript code and can be used to check the performance of your scripts.
Network This tab is for determining the traffic being sent across the network. It shows you all the traffic related to a page. You can see the time it takes for each item on a webpage to load and render.

 

Trying to cover every tab in detail is too much for one blog, but let me help you get started by introducing today’s My 5:

My 5 favourite features in the Internet Explorer F12 Developer Tools

(that’s what they call ‘em so now you know what keywords to use when you bing it, yes I said bing, didn’t you see the article?)

1. Find | Select element by click (CTRL+B)

How many times have you had to go digging through your HTML trying to find that one line of text with the missing accent, or a particular image. When you use Select element by click, you can just click on the element in the web browser and the matching HTML will be shown in the HTML pane below! (and there was much rejoicing)

2. Tools | Change User Agent String

You have a user complaining the site doesn’t work, but it works just fine for you, you ask them what browser they are using, it turns out its a different browser from the one you have installed on your machine. Change the User Agent string to one of the preselected browsers, or even specify a custom setting and voila! Now you can experience the web page the as if you were on a different browser. If you just want to check how the website works on different versions of Internet Explorer you can also use the menu option Browser Mode, browser mode will even let you simulate what happens when a user on IE9 visits a page in compatibility mode (I wrote a blog on compatibility mode a while ago, that’s the feature that you can use if you want the great features of IE9 but have to work with websites that seem messed up in IE9).

3. Tools | Outline Elements

Maybe I just like this one because I have a tendency towards making absolutely hideous web pages (I do not have a good eye for what colors look nice and so on), Outline elements helps you identify different parts of the web page. For example you could outline all the <div> tags in yellow, or all the <a> tags in blue so you can quickly find them on the page.

4. The Script Tab – formatting JavaScript

Often JavaScript is minimized on web pages which makes it hard to read. When you go the script tab, you can click on the Tools button and choose Format JavaScript from the drop down button.

ScriptFormatJS

This will turn your JavaScript from this jumbled mess

function EmuController(a,b){this.impression=b;this.containerId=a;DataStore.set($(a),'emuController',this);return this;}copy_properties(EmuController,{fromContainer:function(a){var b=ge(a);if(!b)return null;return DataStore.get(b,'emuController');},getEventClass:function(a){return "emuEvent"+String(a).trim();}});copy_properties(EmuController.prototype,{EVENT_HANDLER_PATH:'/ajax/emu/end.php',CLICK:1,FAN:"fad_fan",event:function(c,b,d,a){var e={eid:this.impression,f:0,ui:this.containerId,en:c,a:1};if(b)e.ed=JSON.stringify(b);if(!a)var a=bagofholding;var f=new AsyncRequest().setURI(this.EVENT_HANDLER_PATH).setData(e).setErrorHandler(a);if(d)f.setHandler(d);f.send();},redirect:function(){var a={eid:this.impression,f:0,ui:this.containerId,en:this.CLICK,a:0,sig:Math.floor(Math.random()*65535)+65536};var b=new URI(this.EVENT_HANDLER_PATH);b.setQueryData(a);goURI(b);}});
var ShortClickHandlers={EVENT_NAME_CAME_BACK:'cameback',onclicked:function(a){if(this.onsite)return;if(a.button!==0||a.getModifiers().any)return;this.click_ts=(+new Date());if(this.listeners!==undefined)for(var b in this.listeners)this.listeners[b].remove();this.listeners={focus:Event.listen(window,'focus',ShortClickHandlers.oncameback.bind(this))};},oncameback:function(c){var b=(+new Date())-this.click_ts;this.listeners[c.type].remove();var a={click_ts:this.click_ts,length:b,trigger:c.type};this.sendData(ShortClickHandlers.EVENT_NAME_CAME_BACK,a);}};
function EmuTracker(a,c){this.base=EmuController.fromContainer(a);!this.base;this.onsite=c;var b=DOM.scry($(a),"a."+EmuController.getEventClass(EmuTracker.EVENT_CLICK));b.each(function(d){Event.listen(d,'click',ShortClickHandlers.onclicked.bind(this));}.bind(this));return this;}copy_properties(EmuTracker,{EVENT_CLICK:1});copy_properties(EmuTracker.prototype,{sendData:function(b,a){this.base.event(b,a);}});
(function(){if(!window.channel){window.channel={};}else if(channel.OK)return;var a='presence/';copy_properties(channel,{ON_CONNECT:a+'connect',ON_IDLE:a+'idle',ON_SHUTDOWN:a+'shutdown',ON_INVALID_HISTORY:a+'invalid_history',ON_CONFIG:a+'config',ON_ENTER_STATE:a+'enter_state',ON_EXIT_STATE:a+'exit_state',OK:'ok',ERROR:'error',ERROR_CONN:'error_conn',ERROR_MAX:'error_max',ERROR_MISSING:'error_missing',ERROR_MSG_TYPE:'error_msg_type',ERROR_REFRESH:'error_refresh',ERROR_SHUTDOWN:'error_shutdown',ERROR_DOS:'error_dos',HINT_AUTH:'shutdown auth',HINT_CONN:'shutdown conn',HINT_MAINT:'shutdown maint',reason_Unknown:0,reason_AsyncError:1,reason_TooLong:2,reason_Refresh:3,reason_RefreshDelay:4,reason_UIRestart:5,reason_NeedSeq:6,reason_PrevFailed:7,reason_IFrameLoadGiveUp:8,reason_IFrameLoadRetry:9,reason_IFrameLoadRetryWorked:10,reason_PageTransitionRetry:11,reason_IFrameLoadMaxSubdomain:12,reason_NoChannelInfo:13,reason_NoChannelHost:14,reason_ChannelUnknown:100,reason_ChannelNoCUser:101,reason_ChannelInvalidCUser:102,reason_ChannelInvalidChanstr:103,reason_ChannelChDistribTimeout:104,reason_ChannelGetChannelOther:105,reason_ChannelNodeShutdown:106,reason_ChannelTermination:107,reason_ChannelUserMismatch:108,reason_ChannelUserMismatchShady:109,reason_ChannelBadXs:110,reason_ChannelSeqNeg:111,reason_ChannelSeqTooBig:112,reason_ChannelSeqTooSmall:113,reason_ChannelUnexpectedJoin:114,reason_ChannelInvalidXsCookie:115,reason_ChannelRelocate:116,reason_ChannelWrongPartition:117,getArbiterType:function(b){return a+'message:'+b;}});})();
(function(){if(window.channel_cookie)return;window.channel_cookie={subdomainIndex:null,init:function(){var a=presenceCookieManager.getSubCookie('ch');this.retryInterval=presenceCookieManager.getSubCookie('ri')||0;if(!channel.getConfig('nosubdomain')){this.subdomainIndex=0;if(a&&a.sub){for(var b=0;b<a.sub.length;b++)if(!a.sub[b]){this.subdomainIndex=b;break;}if(b==a.sub.length)if(b==channel_manager.MAX_SUBDOMAINS&&URI().isSecure()){this.subdomainIndex=null;presence.error('channel: iframe max subdomains reached');channel_manager._sendIframeError(ChannelRebuildReasons.IFrameLoadMaxSubdomain);}else this.subdomainIndex=a.sub.length;}}presenceCookieManager.register('ch',this.getInfo.bind(this));var c=(function(){this._clearSubdomain=true;presence.doSync(true);}).bind(this);if(typeof window.onpageshow!='undefined'){Event.listen(window,'pagehide',c);}else onunloadRegister(c);},getInfo:function(){var b={};var c=channel.getConfig('host');var e=channel.getConfig('port');if(c){if(null!==this.subdomainIndex){var a=presenceCookieManager.getSubCookie('ch');var f=(a&&a.sub)?a.sub:[];var d=f.length;f[this.subdomainIndex]=this._clearSubdomain?0:1;b.sub=f.map(function(g){return g?1:0;});}b[channel.getConfig('user_channel')]=channel.getConfig('seq',0);}b.ri=this.retryInterval;return b;}};})();
(function(){if(!window.channel){window.channel={};}else if(channel.init)return;copy_properties(channel,{inner:function(){return this.manager.transport._iframe.contentWindow.transport;},_sitevars:{},_config:{userActive:new Date().getTime(),sessionID:(Math.random()*2147483648|0).toString(16)},init:function(){channel_cookie.init();this._config.subdomainIndex=channel_cookie.subdomainIndex;this.log=bind(this,'_log','log');this.error=bind(this,'_log','error');this.warn=bind(this,'_log','warn');if(typeof(UserActivity)!='undefined')UserActivity.subscribe(function(){this._config.userActive=new Date().getTime();}.bind(this));},_log:function(b,c){var d=this.manager&&this.manager.transport;var a='channel2:'+(d?(d.logName+':'):'');if(b=='log'){return false;}else if(b=='warn'){return presence.warn(a+c);}else if(b=='error')return presence.error(a+c);},log:function(a){this._log('log',a);},warn:function(a){this._log('warn',a);},error:function(a){this._log('error',a);},configure:function(){$A(arguments).each(copy_properties.bind(null,this._config));Arbiter.inform(channel.ON_CONFIG,this);},getConfig:function(b,a){return b in this._config?this._config[b]:a;}});})();
function SimpleDrag(a){Event.listen(a,'mousedown',this._start.bind(this));}Class.mixin(SimpleDrag,'Arbiter',{_start:function(event){this.inform('start',event);var b=ua.ie()<9?document.documentElement:window;var a=Event.listen(b,{selectstart:Event.prevent,mousemove:this.inform.bind(this,'update'),mouseup:function(event){for(var c in a)a[c].remove();this.inform('end',event);}.bind(this)});return false;}});
function ScrollableArea(){}copy_properties(ScrollableArea,{getInstance:function(a){var b=Parent.byClass(a,'uiScrollableArea');return b?DataStore.get(b,'ScrollableArea'):null;}});ScrollableArea.prototype={init:function(a,b){b=b||{};this._elem=a;this._wrap=DOM.find(a,'div.uiScrollableAreaWrap');this._body=DOM.find(this._wrap,'div.uiScrollableAreaBody');this._track=DOM.find(a,'div.uiScrollableAreaTrack');this._gripper=DOM.find(this._track,'div.uiScrollableAreaGripper');this._options=b;this.adjustGripper();this._listeners=[Event.listen(this._wrap,'scroll',this._handleScroll.bind(this))];if(b.fade!==false)this._listeners.push(Event.listen(a,'mouseenter',this.adjustGripper.shield(this)),Event.listen(a,'mouseenter',this.showScrollbar.shield(this)),Event.listen(a,'mousemove',this._handleMousemove.bind(this)),Event.listen(a,'mouseout',this.hideScrollbar.shield(this)));this.initDrag();DataStore.set(this._elem,'ScrollableArea',this);if(!b.persistent)onleaveRegister(this.destroy.bind(this));},initDrag:function(){var a=new SimpleDrag(this._gripper);a.subscribe('start',function(b,event){if(!((event.which&&event.which===1)||(event.button&&event.button===1)))return;var d=this._getPageY(event);var e=this._gripper.offsetTop;var f=a.subscribe('update',function(g,event){var j=this._getPageY(event)-d;var i=this._elem.clientHeight;var h=this._body.offsetHeight;var p=this._track.offsetHeight;var k=i/h*p;var m=h-this._wrap.offsetHeight;var l=e+j;var n=p-k;l=Math.max(Math.min(l,n),0);var o=l/n*m;this._wrap.scrollTop=o;}.bind(this));var c=a.subscribe('end',function(){a.unsubscribe(f);a.unsubscribe(c);});}.bind(this));},adjustGripper:function(){var b=this._elem.clientHeight;var a=this._body.offsetHeight;var e=this._track.offsetHeight;var c=b/a*e;if(c<e){CSS.setStyle(this._gripper,'height',c+'px');var d=this._wrap.scrollTop/a*e;CSS.setStyle(this._gripper,'top',d+'px');CSS.show(this._gripper);}else CSS.hide(this._gripper);this._checkContentBoundaries();return this;},_checkContentBoundaries:function(){var a=this._wrap.scrollTop;var b=this._wrap.scrollHeight-this._wrap.clientHeight;CSS.conditionClass(this._elem,'contentBefore',a>0);CSS.conditionClass(this._elem,'contentAfter',a<b);},destroy:function(){this._listeners.forEach(function(a){a.remove();});this._listeners.length=0;},_getPageX:function(event){return event.pageX!=null?event.pageX:event.clientX+document.body.scrollLeft;},_getPageY:function(event){return event.pageY!=null?event.pageY:event.clientY+document.body.scrollTop;},_handleMousemove:function(event){var a=Vector2.getElementPosition(this._track).x;var b=Vector2.getElementDimensions(this._track).x;if(Math.abs(a+b/2-this._getPageX(event))<25){this.showScrollbar(false);}else this.hideScrollbar();},_handleScroll:function(event){this.adjustGripper();if(this._options.fade!==false)this.showScrollbar();},hideScrollbar:function(){if(!this._scrollbarVisible)return this;this._scrollbarVisible=false;if(this._hideTimeout){clearTimeout(this._hideTimeout);this._hideTimeout=null;}this._hideTimeout=function(){if(this._scrollbarAnimation){this._scrollbarAnimation.stop();this._scrollbarAnimation=null;}this._scrollbarAnimation=animation(this._track).from('opacity',1).to('opacity',0).duration(250).ondone(CSS.addClass.curry(this._track,'invisible_elem')).go();}.bind(this).defer(750);return this;},showScrollbar:function(a){if(this._scrollbarVisible)return this;this._scrollbarVisible=true;if(this._hideTimeout){clearTimeout(this._hideTimeout);this._hideTimeout=null;}if(this._scrollbarAnimation){this._scrollbarAnimation.stop();this._scrollbarAnimation=null;}CSS.setStyle(this._track,'opacity',1);CSS.removeClass(this._track,'invisible_elem');if(a!==false)this.hideScrollbar();return this;},scrollToBottom:function(){animation(this._wrap).to('scrollTop',this._wrap.scrollHeight).ease(animation.ease.end).go();}};
FriendRequestMessage={STATUS:'FriendRequest/change',UNFRIEND:

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

To this nicely formatted and readable code

function EmuController(a,b){
    this.impression=b;
    this.containerId=a;
    DataStore.set($(a),'emuController',this);
    return this;
}
copy_properties(EmuController,{
    fromContainer:function(a){
        var b=ge(a);
        if(!b)return null;
        return DataStore.get(b,'emuController');
    }
    ,getEventClass:function(a){

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

5. The Network Tab for Audio and Video

Video and Audio can be a real challenge to work with, and when a video doesn’t play I am never sure if the problem is with my code, the MIME type settings, browser compatibility, or the video itself! By using the network tab to capture my page load I was able to determine whether the problem when my HTML5 video or audio element didn’t work was due to MIME type issues by checking the value in the Type column for that element on the page. You can use the network tab for lots of other great profiling as well, but I have found the type column a nice easy way to check my MIME types.

If you haven’t had a chance yet download the latest version of Internet Explorer today and start trying out the F12 Developer Tools!

This blog post is also available on the Canadian Developer Blog

Advertisements

Console.Log : Say Goodbye to JavaScript Alerts for Debugging!

Admit it, you’ve done it. You have a bug somewhere in your web page and you add an alert to popup a useful message like “I am in the if statement” or “varName=Bob” to help you figure out what is wrong with your code. In IE9 we have an alternative: the Console object.

ASP.NET programmers who work in Visual Studio may already be familiar with the debug object. You call methods of the debug class in your .NET code to display messages in the Output window to help you debug your code in Visual Studio. The Console object is the IE9 equivalent.

Hopefully you have already discovered the Developer tools in IE8 and IE9. If not, just open your browser and go to a website, any website will do. Now hit F12. This will bring up the developer tool window. Now go to the Console tab.

image

Now try typing console.log(“Hello world”) in the console command line at the bottom of the window. Your output should look something like this.

image

console.log will display the parameter passed to the log method in the console window. Use this method to display a string or variable in the console window.

You can use the console class in your code as well, much like we can use JavaScript alerts.

<script type = "text/javascript">
    function tryConsole() {
        console.log("hello world");
    }
</script>

Keep in mind you will not be able to see the output unless you have the developer tools open. You can see the console output on either the Console or Script tabs. Be careful when using console for debugging. If you leave a call to the console object in your code when you move to production and you do not have the developer tools displayed you will get an error message telling you console is undefined. You will get the same error in Visual Studio if you Start without debugging.

image

To avoid the error message, you either need to remove all the console method calls from your code, or you need to add a check to make sure console exists before calling any methods. For example:

<script type = "text/javascript">
    function tryConsole() {
        if (typeof console != "undefined") {
            console.log("hello world");
        }
    }
</script>

Now that you understand the the basics, let’s look at the different methods available with the console class.

log(message[,object]) – the Log method accepts one or more parameters and displays them in the output window. It also accepts format strings.

image

warn(message[,object]) – accepts one or more parameters and format strings just like the log method, but displays the output with a warning icon.

info(message[,object]) – will display an information icon beside the output

error(message[,object]) – will display an error icon beside the output

imageclear() – will clear the console output window

dir(object) –is an object inspection method that will list all the properties of an object

image

assert(expression, message[,object]) – will display the message or object contents if the expression is false

var debugging=false;
console.assert(debugging,"You are not debugging");

So there you have it, more tools to help you debug your web pages. No add-ons or extra software required. Just download IE9 and try it for yourself!

Since we are already playing around in the developer tools that brings me to today’s My 5

My 5 Cool Features in the F12 Developer Tools (in no particular order)

  1. Select element by click – Ever had trouble tracking down the HTML code for a particular element on your page. Select Find | Element by Click from the developer tools menu and then you can just click the element on the web page. The corresponding code in your HTML will be highlighted.
  2. Format JavaScript – It’s all about performance, we compress our JavaScript to reduce the number of bytes that are sent across the network, but then the code becomes almost unreadable to the human eye. Select the Script Tab, choose the Toolbox drop down (the little picture of the hammer and wrench) then select Format JavaScript. Bingo now your JavaScript is readable again!
  3. Browser mode – Developing for IE9 but want to know what your website will look like in IE8 or IE7? Just set the Browser Mode in the menu.
  4. Resize – How does your website appear on a smart phone? how about a tablet or slate? Choose Tools | Resize and then select a size or enter a custom size to ensure your website is user friendly on smaller devices.
  5. Change User Agent String – Debugging a web site that doesn’t seem to work in IE9? Could it be the programmer has written their code to use browser detection instead of feature detection so perhaps the code doesn’t know to check for IE9? You can change the user agent string and see if it works when the code thinks it is being displayed in another browser. Choose Tools | Change user agent string and select the desired value.
    This blog is also posted on Canadian Web Developer