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.