http://michaelsync.net/2007/09/15/firebug-tutorial-commandline-apijavascript
简介php
命令行是firebug中最有用的功能之一。若是你在使用VS中有些经验,当调试的时候,你可能知道VS的“immediate window”和“watch window”。css
firebug的命令行就像VS中的"immediate window"同样,你能够在任什么时候候检查特定的对象的值。更好的是,firebug的命令行也能够在设计的时候使用(注意:vs 的"immediate"窗口只能在调试的时候使用)。而且,另一个优点是你能够在命令行写javascript代码而后实时地执行它。html
命令行的接口列表能够在firebug的官方网站上找到【连接:http://getfirebug.com/commandline.html】。在这个指南中,我要写些使用命令行的例子。我但愿你以为他有用。java
命令行的类型node
在控制台面板中有两种命令行的类型。web
单行命令行ajax
多行命令行express
单行命令行api
这个是firebug控制台面板中默认的。它容许你一次写一个。单行命令行的优点是它支持自动完成功能。
什么是自动完成?(参考http://getfirebug.com/cl.html)
使用tab键你能够自动完成变量的名字和对象属性。不断的敲它,你能够循环全部的可能性集合,用shift+tab后退。
自动完成工做在不少层次。你能够直接按下tab键来循环全局变量,而不用输入任何东西。你能够输入“document.b”,再按TAB,来遍历所 有以"b"开头的属性。你甚至能够输入一个复杂的表达式像“document.getElementsByTagName(’a')[0].”来看文档中 第一个连接的全部属性。另外,你可使用“上”“下”获得你刚才输过的命令。
多行命令行
多行命令行是单行命令行的加强版。它容许你不止一次输入js代码。而且,你能够随时执行这些代码。
单行和多航模式都有他们本身的优势。你能够根据你要作的东西来选择使用哪个。对我来讲,我绝大数状况下是使用单行命令模式。
命令行接口的例子
在读这个指南以前,注意因此的接口均可以在设计和调试的时候使用。然而,当你在调试模式的时候,这个是更有用的。我要告诉你这些是由于你可能在考虑你为何须要这些API
下载~ Demo Zip File
api列表
#1.$(id)
根据特定ID返回单个元素。
这个是js中document.getElementById(”)的缩写版
例子(1.0)~
<body>
Name : <input id="nameTextBox" class="normalText" type="text" />
</body>
怎么作:
输出~
它看起来很是简单(可是不是很是有用),可是我要说的是,当你在调试模式的时候或者是在多命令行写脚本的时候很是有用。
让咱们看看怎样使用多命令行模式,怎样即时执行javascript.
var txt = $('nameTextBox');
txt.value = 'Michael Sync';
txt.textAlign = 'center';
txt.style.color = 'blue';
txt.style.borderStyle = 'double';
txt.style.borderColor = 'pink';
结果~~
#2.$$(选择符)
返回一个匹配特定css选择符的数组。
例子( 1.1 )~
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Firebug</title>
<style type="text/css">
div{
background-color:Black;color:White; border: solid 1px grey;
}
</style>
</head>
<body>
<div id='div1'>This is DIV1.</div>
<br />
<div id='div2'>Here is one more.</div>
</body>
</html>
注意:我在这个例子中使用了“css类型选择符”
步骤:
#3.$x(xpath)
返回一个匹配特定xpath表达式的元素集合。
注意:若是你不了解XPath,你能够看下xpath指南here [^].
例子(1.2)~
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>CommandLine - $</title>
</head>
<body>
<div id='container' style="width:800px">
<div id='leftsidebar' style="width:100px; background-color:Gray;min-height:400px;float:left;"> </div>
<div id='content' style="width:600px;min-height:400px; background-color:ThreeDShadow;float:left;">
<div id='content-header' style="padding:2px;font-family:Calibri,Trebuchet MS;">
<h2>All about Firebug</h2>
</div>
<div id='content-body' style="padding:2px;font-family:Calibri,Trebuchet MS;">
<p>Firebug is the most popular tool in web revolution.</p>
</div>
</div>
<div id='rightsidebar' style="width:100px; background-color:Gray;height:400px;float:right;"></div>
</div>
</body>
</html>
咱们将要在多行命令行中测试。
把这个代码粘贴在多行命令行模式。
var obj = $x('html/body/div/div');
console.log(obj[0].id);
console.log(obj[1].id);
console.log(obj[2].id);
结果~
#4.dir(object)
输出和这个对象有关的全部属性的列表。这个和你在点击dom选项卡后看到的效果同样。
它像我在第一部分中提到的console.write()。全部我认为你已经有些想法了关于console.dir是什么而且怎么使用。这个例子,我将不使用新的HTML代码,而是使用前边的例子代替(例1.2)而且我将改变在多行命令行中的代码。
var obj = $x('html/body/div/div');
<strong>dir(obj);</strong>
下边的图片显示出了这个例子的结果。你将会获得这三个div对象的全部属性和方法。(leftsidebar, content, rightsidebar)
#5. dirxml(note)
输出一个html和xml元素的XML资源树,这个和你直接单击html选项卡同样。你能够单击任何一个节点来查看。
#6. cd(window)
默认状况下,命令行表达式和页面最高层的窗口有关。cd()容许你使用在页面中框架的窗口。
注意:这个API看上去不能正常工做。我将通知firebug团队而且让大家知道结果。
#7. clear()
清除控制台。若是你想清除控制台,输入这个命令“clear()”按回车。你也可在在js代码中输入"cosole.clear()".
#8. inspect(object[,tabName])
在一个最合适的标签中检查对象,或是经过可选的参数实现标签识别可用的标签名字是“html”, “css”, “script”, 和“dom”.
步骤~
#9. keys(object)
返回一个数组,数组中包含这个标签的对象的全部属性的名字。这个对象能够是js对象( eg: var objCar = new Car() )或者是html对象(eg: document.getElementById(’table1′))。
例1.4~
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Keys and Values</title>
</head>
<body>
<table id="tbl1" cellpadding="0" cellspacing="0" border="0">
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
</table>
<script language="javascript" type="text/javascript">
function Car(){
this.Model = "Old Model";
this.getManufactor = new function(){
return "Toyota";
}
}
</script>
</body>
</html>
步骤~
注意:若是你想练习这个API,请试着用这个API获得名叫“tbl1”表的全部属性的名字。让我知道你获得的结果是什么。
#10. values(object)
返回一个数组,数组中含有这个对象的全部属性的值。
例子:参考 例1.4
步骤~
注意:由于getManufactor是个函数,因此它显示"object"(绿色连接),而不是值"Toyota"
#11. debug(fn) and undebug(fu)
在函数的第一行添加或者移除一个断点。
注意:在这个指南中,我不介绍这个API。关于这个,请读下个部分。
#12. monitor(functionName) and unmonitor(functionName)
打开/关闭函数调用记录日志
一般,若是咱们想知道一个特定的函数是否被激发。咱们一般使用"alert()"或者"console.log()"。若是咱们使用了不少js文 件,那就是一个至关大的工做量了。由于咱们须要在全部的js文件中找到这个函数,而后再放上"alert()"或者是"console.log",而且再 一次保存那个文件而后在浏览器中运行。用了firebug你不须要作那些事情了。你只须要知道这个函数,你能够跟踪他被执行了多少次。当你监视的那个函数 被激发后,你能够在控制台中获得通知。另外,它将会给你指向这个函数的连接。
例1.5~
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Monitor and Profiler</title>
<script type="text/javascript">
function func1(){
//doSomething
}
function func2(){
//doSomething
}
function func3(){
//doSomething
}
</script>
</head>
<body>
<input id="btn1" type="button" value="Invoke func1()" onclick="func1();"/>
<input id="btn2" type="button" value="Invoke func2()" onclick="func2();"/>
<input id="btn3" type="button" value="Invoke func3()" onclick="func3();"/>
</body>
</html>
步骤~
结果~
#13. monitorEvents(object[, types]) and unmonitorEvents(object[, types])
快速打开或关闭对一个对象的全部事件的记录
可选参数"types"能够具体指定一个具体的事件集合来记录。最经常使用的值是"mouse"和"key"
这些可用的类型的列表包括composition”, “contextmenu”, “drag”, “focus”, “form”, “key”, “load”, “mouse”, “mutation”, “paint”, “scroll”, “text”, “ui”, 和“xul”
注意:不幸的是,这个API不能正常工做。之后我将和firebug团队联系而且更新她,对不起。
#14. profile([title]) and profileEnd()
打开和关闭javascript profiler。这个可选的参数标题包含在报告头中输出的文本。有三种方式能够打开javascript profiler
若是你想知道更多关于在firebug中profiler的信息。请阅读我之前的指南(Firebug Tutorial - Logging, Profiling and CommandLine (Part II)).
总结
这个都是关于控制台选项卡的。即便仅仅一个选项卡,我也必须把个人指南分红三部分part 1, part 2 和这个)。如今我如今已经解释了关于控制台选项卡的全部事情。但愿你以为他有用
若是你有任何意见或者建议,请联系我。
Section 1: Console Tab : Logging, Profiling and CommandLine (Part II)
Overview of Console Tab
This tab is mainly used for logging. It also can be used as CommandLine window (like immediate window in Microsoft Visual Studio) while you are debugging the Javascript. It can be used for monitoring the execution of Javascript code by using Profiling service.
The following topic will be covered in this section.
#1. Logging in Firebug
Firebug supports logging in Console tab. So, you don’t need to use alert(‘something’) or document.write(‘something’) anymore.
There are five types of logging in Firebug.
Example Code:
1 2 3 4 5 6 7 |
<script language="javascript" type="text/javascript"> console.log('This is log message'); console.debug('This is debug message'); console.error('This is error message'); console.info('This is info message'); console.warn('This is warning message'); </script> |
You will get the following output. If you click on hyperlink (“test.htm” in this case), it will take you to script tab and will highlight the line that wrote this message.
String Substitution Patterns
String substitution parterns can be used in console.log, console.info, console.debug, console.warn and console.error . You can use the same way that we used in C/C++.
%s |
String |
%d, %i |
Integer (numeric formatting is not yet supported) |
%f |
Floating point number (numeric formatting is not yet supported) |
%o |
Object hyperlink |
Example :
Note: I will use console.log in the example below even all console objects (console.log, console.info, console.debug, console.warn and console.error ) support string substitution.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<script language="javascript" type="text/javascript">
//This is for normal string substitution " %s, %d, %i, %f". console.log("My Name is <strong>%s</strong>. My Date of Birth is <strong>%dth %s, %i</strong>. My height is <strong>%f</strong> m.", "Nicolas Cage", 7, 'January', 1964, 1.8542);
function Foo(){ this.LeftHand = function(){ return "Left Hand"; } this.RightHand = function(){ return "Right Hand"; } }
//This is for object "%o". var objFoo = new Foo(); console.log('This is <strong>%o</strong> of Foo class.', objFoo);
</script> |
If you are using %o in your log, the object will be shown as a hyperlink in green color. This hyperlink is linked to the DOM tab. So, If you click “object” in second line, you will see the list of properties of that object (LeftHand and RightHand in this case.)
#2. Grouping
Firebug allows you to group the message or log in Console tab. If you have some many logs in your code, you can probably divide your log into small group or subgroup
Example ~
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<script language="javascript" type="text/javascript">
var groupname = 'group1'; console.group("message group : %s " , groupname); console.log("log message 1 from %s", groupname); console.log("log message 2 from %s", groupname); console.log("log message 3 from %s", groupname); console.groupEnd();
groupname = 'group2'; console.group("message group : %s " , groupname); console.log("log message 1 from %s", groupname);
var subgroupname = 'subgroup1'; console.group("message group : %s " , subgroupname); console.log("log message 1 from %s", subgroupname); console.log("log message 2 from %s", subgroupname); console.log("log message 3 from %s", subgroupname); console.groupEnd();
console.log("log message 3 from %s", groupname); console.groupEnd();
</script> |
#3. console.dir and console.dirxml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<table id="tbl1" cellpadding="0" cellspacing="0" border="0"> <tr> <td>A</td> <td>B</td> <td>C</td> </tr> </table> <script language="javascript" type="text/javascript"> //Create a class function Car(){ this.Model = "Old Model";
this.getManufactor = new function(){ return "Toyota"; } }
//Create a object var objCar = new Car();
//Firebug console.dir(objCar); console.dirxml(document.getElementById('tbl1'));
</script> |
#4. Assertion ( console.assert() )
You can use console.assert() to test whether an expression is true or not. If the expression is false, it will write a message to the console and throw an exception.
Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<script language="javascript" type="text/javascript"> function whatIsMyAge(year){ var currYear = 2007; return currYear - year; }
var yearOfBirth1 = 1982; var age1 = 25; console.assert(whatIsMyAge(yearOfBirth1) == age1);
var yearOfBirth2 = 1982; var age2 = 11; console.assert(whatIsMyAge(yearOfBirth2) == age2); //You should get the error here. </script> |
#5. Tracing ( console.trace() )
This function is very interesting. Before I tell you the way that I understand, let’s take a look what console.trace does exactly in official website.
console.trace()
Prints an interactive stack trace of JavaScript execution at the point where it is called.
The stack trace details the functions on the stack, as well as the values that were passed as arguments to each function. You can click each function to take you to its source in the Script tab, and click each argument value to inspect it in the DOM or HTML tabs.
This function will tell you about the route information from start point to end point. If you are not clear what I mean, let’s take a look at the sample code and the result.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Firebug</title> <script language="javascript" type="text/javascript"> function startTrace(str){ return method1(100,200); } function method1(arg1,arg2){ return method2(arg1 + arg2 + 100); } function method2(arg1){ var var1 = arg1 / 100; return method3(var1); } function method3(arg1){ console.trace(); var total = arg1 * 100; return total; }
</script> </head> <body> <input type="button" value="Trace" onclick="startTrace('Result');"/> </body> </html> |
Suppose: we wanna know how “method3″ function is invoked. So, we put this code “console.trace()” in that method. then, we run the program and we got the result as picture above. If we read the result from bottom to top, we will see “onclick(click clientX=34, clientY=26)”. That means the execution of Javascript started at on click event of button. then, we got “startTrace(“Result”)” in second line. That means startTrace function is invoked after firing onclick event and the parameter is “Result”. If we keep on checking from bottom to top, we will figure out the completed route from onclick event to method3.
If you wanna test more, you can move this code “console.trace()” to method2(). then, firebug will give the new route from onclick event which is a started point to method2() which is the end point.
I think that it’s pretty useful if you are debugging the other developer’s source code and you have no idea why this function is invoked.
Let me know if you are not clear what I’m trying to explain about console.trace();.
#6. Timing ( Measuring the time of your code)
You can use console.time(timeName) function to measure how long a particular code or function take. This feature is very helpful if you are trying to improve the performance of your Javascript code.
Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Firebug</title> <script language="javascript" type="text/javascript"> function measuretheTime(){ var timeName = 'measuringTime'; console.time(timeName);
for(var i=0;i<1000;i++){ ///do something for(var j=0;j<100;j++){ //do another thing. } }
console.timeEnd(timeName); } </script> </head> <body> <input type="button" value="Trace" onclick="measuretheTime();"/> </body> </html> |
Result : measuringTime: 16ms
#7. Javascript Profiler
You can start the profiler thought code (console.profile(‘profileName’)) or by clicking “Profile” button from “Console” tag. It can be used for improving the performance of Javascript. It is similiar to the console.time() function but profiler can give your more advanced and detailed information.
I will tell you about this more details in next tutorial (Part2) . I hope you all are clear about this tutorial. If you have any comment or suggestion, please drop a comment.. Thanks. C ya tomorrow.
Reference ~
Firebug Tutorial
Section 1: Console Tab : Logging, Profiling and CommandLine (Part II)
Introduction
This tutorial is the part II of “Firebug Tutorial – Logging, Profiling and CommandLine“. (If you haven’t read the part I of this tutorial, I would recommend you to read the part 1 first.)
The following topic will be covered in this section.
#1. Javascript Profiler
Javascript Profiler is very useful feature of Firebug for measuring the execution time of each javascript code. It is useful for improving the performance of your code or if you wanna find out why a particular function takes soooo long. It is a bit similar to console.time() that I mentioned already to previous part but Javascript Profiler can give you more detailed information about what’s happening with your code.
There are three ways to use Javascript Profiler. You can call this function by clicking “Profile” button on the toolbar of Firebug console or through code “console.profile()” or by typing “profile()” in commandline. I will cover first two in this tutorial but not for using profile() in commandline. If you want to know how to use it in commandline, please check-out this article.
console.profile()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Firebug</title> <script language="javascript" type="text/javascript">
function startDoSomething(){ <strong>console.profile('Measuring time');</strong> doSomething(); <strong>console.profileEnd();</strong> } function doSomething(){ doThis(1000); doThis(100000); doThat(10000); doThisAndThat(1000,10000);
} function doThis(count){ for(var i=0;i<count;i++){} }
function doThat(count){ for(var i=0;i<count;i++){} }
function doThisAndThat(countThis,countThat){ for(var i=0;i<countThis;i++){ for(var j=0;j<countThat;j++){} } } </script> </head> <body> Open the console tab. Click the button below and wait a lit.. <br /> <input type="button" value="Start" onclick="startDoSomething();"/> </body> </html> |
(The list is sorted based on the execution time.)
Columns and Description of Profiler
Note: You can set the title of profiler by passing one string to console.profile() function. In our example (console.profile(‘Measuring time’);), ‘Measuring time’ is the title of profiler.
Profiler button from Console tab’s toolbar
If you don’t want to profile thru the code, you can use “Profile” button from the toolbar of Firebug console.
In order to test this,
That’s all about Javascript Profiler. Let me know if you have any question or comment.
Okay. Let’s move on to next topic.
#2. Options of Console tab
There is one link called “Options” at the right-side of Firebug console. If you click this link, you will see the menu as shown in picture below.
I will divided those times in three categories.
#2.1 Errors Tracing and Filtering
Those options are used for tracing the errors of your script, style sheet and XML. You can also filter the error messages based on the type of error that you wanna.
Example Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Firebug</title> <style type="text/css"> .normalText{ bcolor : red; /* This is ERROR!! */ } </style> <script language="javascript" type="text/javascript"> function foo(){ var objTxt = doucmnet.getElementById('nameTextBox'); //This is ERROR!! alert(objTxt.value); } </script> </head> <body>
<input id="nameTextBox" class="normalText" type="text" /> <input type="button" value="Start" onclick="foo();"/> </body> </html> |
Output ~
I think those options are very sample to use. If you wanna see the errors, just check the option in menu. then, Firebug will give very good information about the errors that you are getting. Uncheck it if you don’t want.
#2.2. Tracing XmlHttpRequest object
This is also one of the most popular feature of Firebug and it is really helpful for Ajax developer. The problem with Ajax is that it is very difficult to figure out if something goes wrong in XmlHttpRequest. Sometimes, you have no idea about what’s going on behind the sense while the indicator keep on cycling all the time. One of the problem that I face when I was playing around with ajax, it is difficult to find out whether the response format from Web service are correct or not.
but things are very simple with Firebug. You only need to select “Show XmlHttpRequest” option. Firebug will tell the following thing.
Example : I used Yahoo UI DataTable in this sample. This sample is the updated version of this sample from Yahoo UI.
Download : SourceCode
Note: If you don’t wanna download or if you don’t have PHP installed on your machine, you may try to check this online sample from Yahoo. But there won’t be any button so you should select the “Show XmlHttpRequests” option first and reload or open the link…
Okay. That’s all for today. I was thinking to write about CommandLine in this part but I don’t have the enough time to write it today. Don’t worry. I will tell about CommandLine tomorrow.
Cya. Don’t hesitate to drop a comment if you have any suggestion or comment. I appreciate it.