開篇概述
在上篇部落格中詳解Google Chrome浏覽器(理論篇)一文中,主要講解了Chrome 搜尋引擎使用、Chrome安裝和基本操作、Chrome 基本架構、多線程等原理性問題,這篇将重點講解Chro-me實操問題,主要結合“Chrome 主調試面闆“,對Chrome,Elements,Con-sole,Sources,NetWork,TimeLine,Profiles,Application,Security,Audits進行詳解。若對廣大讀者朋友有所幫助,我将不勝感激。本篇博文主要從 當然了,在閱讀本篇文章前,強烈建議大家先閱讀詳解Google Chrome浏覽器(理論篇)一文。如此,對本篇文章的了解,也許會更加容易些。
溫故而知新
1、Chrome基本架構圖和Chrome主調試面闆

正文
一、Elements面闆
概述
定義: Inspect and Edit Pages and Styles by Elements panel,but also effective immediately.
譯文:通過Elements 面闆,不僅僅可以檢視和編輯頁面和樣式,而且所做的改變立即生效。
詳解
第一部份:操作DOM
1、檢視DOM樹
打開Element面闆,可以檢視所有DOM節點,包括CSS和JavaScript,如下圖所示,左側為DOM樹,右側為CSS樣式。
2、選取DOM節點
将滑鼠移到網頁中的某元素上面,該元素會發生變化如下圖所示:
注釋:
選中的p節點在DOM樹中被精确定位(藍色背景),可以看到p節點的DOM層次(紅色方框),在面闆右側,是p節點的CSS樣式。當然,也可以在Element面闆的DOM樹中選取DOM節點。将滑鼠放到相應的DOM節點上,會發現網頁中相應的節點也發生了變化,點選該節點,即可選中。
4、增加、删除和修改DOM節點
在Element面闆中,選擇DOM節點,在文本處右擊滑鼠,會彈出一個菜單,如下圖所示:
注釋
a、Edit text:編輯該節點中的文本。也可以在文本處輕按兩下進行編輯。
b、Edit as HTML:編輯該節點及其子節點的所有HTML元素(包括節點中的文本)。
c、Copy:複制 。(比較簡單,這裡就不論述了)
(1)Copy outerHTML
(2)Copy selector
(3)Copy XPath
(4)cut element
(5)Copy element
(6)Paste element
d、Hide element:隐藏元素,讓其不在頁面顯示。
e、Delete element:删除元素。
f、Expand all:展開指定節點及其所有子節點。
g、Collapse all:收縮指定節點及其所有子節點。
5、拖動節點,改變節點順序。
6、為節點添加屬性
為<p>節點添加id屬性,如下:
<pid="demo">http://www.itxueyuan.org/javascript/</p>
會在控制台輸出p#demo;再向<p>節點添加class屬性和name屬性,如下:
<pid="demo"class="demo"data="demo">http://www.itxueyuan.org/javascript/</p>
會在控制台輸出p#demo.demo。可見,控制台隻會輸出符合W3C标準的屬性,不支援自定義屬性。不過,實際開發中很少用到該功能。
7、Inspect and live-edit the HTML and CSS of a page using the Chrome DevTools Elements panel.
a、Inspect and edit on the fly any element in the DOM tree in the Elements panel.
b、 View and change the CSS rules applied to any selected element in the Styles pane.
c、View and edit a selected element's box model in the Computed pane.
d、View any changes made to your page locally in the Sources panel.
8、Live-edit a DOM node
To live-edit a DOM node, simply double-click a selected element and make changes:
注釋
The DOM tree view shows the current state of the tree; it may not match the HTML that was originally loaded for different reasons. For example, you can modify the DOM tree using JavaScript; the browser engine can try to correct invalid author markup and produce an unexpected DOM.
9、Live-edit a style
Live-edit style property names and values in the Styles pane. All styles are editable, except the ones that are greyed out (as is the case with user agent stylesheets).
To edit a name or value, click on it, make your changes, and press Tab or Enter to save the change.
By default, your CSS modifications are not permanent, changes are lost when you reload the page. Set up persistent authoring if you want to persist your changes between page loads.
10、Examine and edit box model parameters
Examine and edit the current element's box model parameters using the Computed pane. All values in the box model are editable, just click on them.
The concentric rectangles contain the top, bottom, left, right values for the current element's padding, border, and marginproperties.
For non-statically positioned elements, a position rectangle is also displayed, containing the values of the top, right, bottom, and left properties.
For position: fixed and position: absolute elements, the central field contains the actual offsetWidth × offsetHeight pixel dimensions of the selected element. All values can be modified by double-clicking them, like property values in the Styles pane. The changes are not, however, guaranteed to take effect, as this is subject to the concrete element positioning specifics.
11、View local changes
To view a history of live-edits made to your page:
a、In the Styles pane, click on the file that you modified. DevTools takes you to the Sources panel.
b、Right-click on the file.
c、Select Local modifications.
To explore the changes made:
a、Expand top-level file names to view the time time modification occurred a modification occurred.
b、 Expand second-level items to view a diff (before and after) corresponding to the modification. A line with a pink background signifies a removal while a line with a green background signifies an addition.
12、檢視css樣式
CSS樣式審查面闆是一個非常有用的面闆,實際開發中,有時候CSS樣式表會非常複雜,甚至連我們自己都不知道目前節點應用了哪些樣式。使用CSS樣式審查面闆,可以讓我們清楚地知道目前節點使用了哪些樣式,分别來自哪些檔案,哪些樣式是被覆寫的,哪些樣式是最終樣式,哪些樣式是無效的,等等。
如下圖所示,選中節點,Element面闆右側的CSS樣式審查面闆會展示出該節點的CSS樣式。在CSS樣式審查面闆中,我們可以添加、删除和修改CSS樣式。另外,CSS審查面闆中有幾個子面闆,如下圖所示:
子面闆說明:
a、Style(樣式):目前節點的樣式;
b、Computed(計算):檢視目前節點經過計算後的樣式以及盒模型資料;
c、 Event Listeners(事件監聽):檢視為目前節點綁定的事件和事件監聽函數;
d、 DOM Breakpoints(DOM斷點):檢視為目前節點設定的DOM斷點;
e、 Properties(屬性):目前節點(對象)的所有屬性。
小結
Element 譯為“元素”,Element 面闆可以讓我們動态檢視和編輯DOM節點和CSS樣式表,并且立即生效,避免了頻繁切換浏覽器和編輯器的麻煩。 我們可以使用Element面闆來檢視源代碼,它不但可以很好的格式化DOM節點,清晰的展現HTML文檔,還可以檢視JavaScript建立的DOM節點和iframe中的DOM節點,比在目前網頁中右擊滑鼠選擇“檢視網頁源代碼”強大很多。 總之,Element面闆可以讓我們很透徹的了解DOM和CSS的底層結構。
二、Console面闆
定義:Use the Console API to write information to the console, create JavaScript profiles, and start a debugging session.
譯文:使用Console API向控制台輸出資訊,産生JavaScript檔案和啟動調試會話。
The Console
The console offers a way to inspect and debug your webpages. Think of it as the Terminal of your web content. The console has access to the DOM and JavaScript of the open page. Use the console as a tool to modify your web content via interactive commands and as a teaching aid to expand your knowledge of JavaScript. Because an object’s methods and properties autocomplete as you type, you can see all available functions that are valid in Safari.For example, open the console and type $$(‘p’)[1]. ($$ is shorthand for document.querySelectorAll—see more shorthand commands in Table 5-1.) Because this paragraph is the second instance of the p element on this page ([1] in a 0-based index), the node represents this paragraph. As you hover over the node, its position on the page is visibly highlighted. You can expand the node to see its contents, and even press Command-C to copy it to your clipboard.
Command-Line API
You can inspect HTML nodes and JavaScript objects in more detail by using the console commands listed in Table 5-1. Type the command-line APIs interactively within the console.
If your scripts share the same function name as a Command-Line API function, the function in your scripts takes precedence.
The functions listed in Table 5-1 are regular JavaScript functions that are part of the Web Inspector environment. That means you can use them as you would any JavaScript function. For example, you can assign a chain of Console API commands to a variable to create a useful shorthand. Listing 5-1 shows how you can quickly see all event types attached to the selected node.
After defining this function, inspect the magnifying glass in the top-right corner of this webpage, and type evs() in the console. An array containing the string “click” is returned, because there is a click event listener attached to that element.
Of course, these functions shouldn’t be included in your website’s JavaScript files because they are not available in the browser environment. Only use these functions in the Web Inspector console. Console functions you can include in your scripts are described in Console API.
Console API
1、console.assert(expression, object)
定義:Writes an error to the console when the evaluated expression is false.
譯文:當計算表達式為假時,向控制台輸出錯誤資訊。
示例1:
function greaterThan(a,b) {
console.assert(a > b, {"message":"a is not greater than b","a":a,"b":b});
}
greaterThan(5,6);
result:
示例2:
var isFalse=false;
console.assert(isFalse,"Output Info when evaluated expression is false");
2、console.clear()
定義:Clears the console.If the Preserve log checkbox is enabled, console.clear() is disabled. However, pressing the clear console button () or typing the shortcut Ctrl+L while the Console is in focus still works.See Clearing the console for more information.
譯文:清楚控制台資訊。如果保護日志複選框被啟用,則console.clear()被禁用。然而,當控制台的焦點仍在工作時,按明确的控制台按鈕(明确控制台按鈕)或輸入快捷鍵Ctrl + L。
3、console.count(label)
定義:Writes the the number of times that count() has been invoked at the same line and with the same label.
譯文:輸出被調用相同的行和相同的标簽的總次數。
function login(name) {
console.count(name + ' logged in');
}
4、console.debug(object [, object, ...])
定義:Identical to console.log().
譯文:與console.log()一樣;
小結:功能與console.log()一樣。
5、console.dir(object)
定義:Prints a JavaScript representation of the specified object. If the object being logged is an HTML element, then the properties of its DOM representation are printed.
譯文:列印具體對象的JavaScript表示。如果被記錄的對象是一個HTML元素,然後列印DOM表示的屬性。
console.dir(document)
6、console.dirxml(object)
定義:Prints an XML representation of the descendant elements of object if possible, or the JavaScript representation if not. Calling console.dirxml() on HTML and XML elements is equivalent to calling console.log().
譯文:如果可能,列印對象的後代元素的XML表示,如果不可能,則列印javaScript表示。對于html和xml元素,調用console.dirxml()相當于調用console.log();
console.dirxml(obj)
console.dir(document);
result:
示例3:
console.log(document);
rersult:
7、console.error(object [, object, ...])
定義:Prints a message similar to console.log(), styles the message like an error, and includes a stack trace from where the method was called.
譯文:列印一條類似于console.log()列印的消息,錯誤樣式和包括堆棧跟蹤。
function logName(obj){
if(obj.name==undefined){
console.error('name is undefined')
}
}
logName({});
console.error('print error Information');
8、console.group(object[, object, ...])
定義:Starts a new logging group with an optional title. All console output that occurs after console.group() and before console.groupEnd() is visually grouped together.
譯文:開始一個帶有可選标題的日志組。所有控制台輸出的内容被包含在以console.group()開始和以consol.groupEnd()結束之間。
function name(obj) {
console.group('name');
console.log('first: ', obj.first);
console.log('middle: ', obj.middle);
console.log('last: ', obj.last);
console.groupEnd();
}
name({"first":"Wile","middle":"E","last":"Coyote"});
function name(obj) {
console.group('name');
console.log('first: ', obj.first);
console.log('middle: ', obj.middle);
console.log('last: ', obj.last);
console.groupEnd();
}
function doStuff() {
console.group('doStuff()');
name({"first":"Wile","middle":"E","last":"coyote"});
console.groupEnd();
}
doStuff();
9、console.groupCollapsed(object[, object, ...])
定義:Creates a new logging group that is initially collapsed instead of open.
譯文:建立一個新的初始化倒塌而不是開放的日志組。
示例:
console.groupCollapsed('status');
console.log("peekaboo, you can't see me");
console.groupEnd();
10、console.groupEnd()
定義:Closes a logging group. See console.group for an example.
譯文:建立日志組。以console.group()作為例子。
11、console.info(object [, object, ...])
定義:Prints a message like console.log() but also shows an icon (blue circle with white "i") next to the output.
譯文:不僅列印一條像console.log()一樣的消息,而且也顯示了一個緊挨着輸出結果的圖示(帶有"i"的藍色圈)。
console.info('帶有"i"的藍色圈')
12、console.log(object [, object, ...])
定義:Displays a message in the console. Pass one or more objects to this method.Each object is evaluated and concatenated into a space-delimited string.
譯文:将消息顯示在控制台。将一個或多個對象傳遞給這個方法。每個隊對象被計算成和連接配接成一個空格分隔字元串。
console.log('Hello, Logs!');
13、console.marktimeline()
已經被棄用,已被console.timeStamp替換。
console.markTimeline();
14、console.profile([label])
定義:Starts a JavaScript CPU profile with an optional label. To complete the profile, call console.profileEnd(). Each profile is added to the Profiles panel.
譯文:開始一個帶有可選标簽的JavaScript CPU性能分析。以console.profileEnd()作為整個性能分析結束的标記。每次性能分析結果被附加到性能分析面闆。
function processPixels() {
console.profile("processPixels()");
// later, after processing pixels
console.profileEnd();
}
processPixels();
15、console.profileEnd()
定義:Stops the current JavaScript CPU profiling session if one is in progress and prints the report to the Profiles panel.See console.profile() for an example.
譯文:如果性能分析進行中和把分析報告列印到性能分析面闆,停止目前的JavaScript CPU性能分析會話 。以console.profile作為一個例子。
16、console.table()
定義:displays the data in a table form.The data
argument may be an array or an object.
譯文:将資料以表格形式列印出。資料參數可能為一個數組,也可能為一個對象。
// an array of strings
console.table(["apples", "oranges", "bananas"]);
// an object whose properties are strings
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
var me = new Person("John", "Smith");
console.table(me);
// an array of arrays
var people = [["John", "Smith"], ["Jane", "Doe"], ["Emily", "Jones"]]
console.table(people);
示例4:
// an array of objects
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
var john = new Person("John", "Smith");
var jane = new Person("Jane", "Doe");
var emily = new Person("Emily", "Jones");
console.table([john, jane, emily]);
示例5:
// an object whose properties are objects
var family = {};
family.mother = new Person("Jane", "Smith");
family.father = new Person("John", "Smith");
family.daughter = new Person("Emily", "Smith");
console.table(family);
示例6:
// an array of objects, logging only firstName
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
var john = new Person("John", "Smith");
var jane = new Person("Jane", "Doe");
var emily = new Person("Emily", "Jones");
console.table([john, jane, emily], ["firstName"]);
17、console.time([label])
定義:Starts a new timer. Call console.timeEnd() to stop the timer and print the elapsed time to the Console.
譯文:開始一個新的定時器。調用console.timeEnd()停止定時器,把已記時的時間列印到控制台。
console.time();
var arr = new Array(10000);
for (var i = 0; i < arr.length; i++) {
arr[i] = new Object();
}
console.timeEnd();
console.time('total');
var arr = new Array(10000);
for (var i = 0; i < arr.length; i++) {
arr[i] = new Object();
}
console.timeEnd('total');
console.time('total');
console.time('init arr');
var arr = new Array(10000);
console.timeEnd('init arr');
for (var i = 0; i < arr.length; i++) {
arr[i] = new Object();
}
console.timeEnd('total');
18、console.timeEnd([label])
定義:Stops a timer. See console.time() for examples.
譯文:停止計時器。以console.time()作為一個例子。
19、console.timeStamp([label])
定義:Adds an event to the Timeline during a recording session.
譯文:在一個記錄會話期間,添加一個事件到時間表。
console.timeStamp('check out this custom timestamp thanks to console.timeStamp()!');
result:
20、console.trace(object)
定義:Prints a stack trace from the point where the method was called.
譯文:列印一個堆棧跟蹤的方法。
function add(num){
if(num>0){
//you can pass lables and objects to trace,too.
console.trace('recursion is fun:',num);
return num+add(num-1);
}else{
return 0;
}
}
add(3);
21、console.warn(object [, object, ...])
定義: Prints a message like console.log(), but also displays a yellow warning icon next to the logged message.
譯文:不僅列印像console.log()的消息,而且也顯示一個緊挨着輸出消息的黃色圖示。
console.warn('user limit reached!');
小結:
大緻介紹了Chrome console内置函數,其中,console.log(),console.info(),console.error(),console.warn()需要差別一下。
三、Sources面闆
Sources面闆通過設定斷點來調試 JavaScript ,或者通過Workspaces(工作區)連接配接本地檔案來使用開發者工具的實時編輯器。在上一篇博文本篇部落格詳解Google Chrome浏覽器(理論篇)中概述了Sources面闆的主要功能,即斷點調試、調試混淆的代碼和使用開發者工具工作區進行持久化儲存,本篇文章将結合Sources面闆的主要功能,且從Source面闆三個組成部分來叙述,下圖紅色字型标記。
第一部份:它的功能類似于Resources面闆,主要用來顯示網頁加載腳本檔案,如css,js等資源檔案,但不包括cookie,img等靜态資源檔案。
該部分由三個Tab組成,它們都存在不同域名和環境下的js和css檔案。
a、Sources:包含該項目的靜态檔案,如項目資源檔案css和js。輕按兩下選中檔案,該内容會在第二部分顯示(若選擇JS檔案,則可以在第二部分進行斷點調試)
b、Content scripts:主要是第三方插件和Chrome浏覽器資源問件等
c、Snippets:js片段,允許使用者自設定JS,主要用來測試JS檔案、記住調試片段、單元測試、少了功能代碼編寫等
第二部分
這部分,主要有兩個功能:檢視第一部分選擇的頁面和js調試。主要講解js調試。
a、設定和取消斷點。選擇想要設定斷點的js具體行,點選行号,就設定了斷點,再次點選,就取消已設定的斷點。
b、快捷鍵:F10單步執行,但當遇到方法,不進入方法,直接方法外的下一行代碼。F11單步調試,且遇方法體,需要經過。CTR+F 快速查找比對資源。CTR+G 快速定位檔案具體行。
c、第二部分底部,“{}”表示格式化代碼。
d、第二部分底部,緊挨{}處右側,表示目前光标行号和列号。
第三部分
a、頂部圖示說明
b、Watch:為目前斷點添加表達式。注:程式每執行一行代碼,都會執行自定義添加的表達式,某些時候,會嚴重影響程式性能。
c、Scope監視環境變量,私有變量、公有變量、全局變量等。
總結
本想在本篇博文就将Chrome講完的,但寫到這,感覺篇幅比較長了,經過認真考慮,還是分為兩篇博文來寫。
本篇博文主要寫了Chrome DevTool 前三面闆:Elements,Console和Sources,在接下來的另一篇博文中,将接着寫剩下的部分:Network,Timeline,Profiles,Application,Security,Audits面闆。
當然了,我寫部落格的目的,不僅僅是為了與廣大博友分享知識,更希望能從讀者朋友們的回報中,學到知識,以求達到共同學習,共同進步的目的。是以,廣大讀者朋友們,若對本篇博文有任何高見和建議,歡迎指出,如此,非常感謝!!!
參考
【1】http://web.jobbole.com/82562/
【2】https://developer.chrome.com/devtools
【3】http://zhangzhaoaaa.iteye.com/blog/2247890
【4】http://www.cr173.com/gonglue/62840_1.html
【5】https://segmentfault.com/a/1190000002511877
【6】https://segmentfault.com/a/1190000004123527
【7】http://www.cnblogs.com/zhongxinWang/p/4121111.html
【8】https://developers.google.com/web/tools/chrome-devtools/
【9】https://developer.mozilla.org/zh-CN/docs/Web/API/Console/table
【10】http://jingyan.baidu.com/article/2f9b480db6cde741ca6cc246.html
【11】https://developers.google.com/web/tools/chrome-devtools/console/console-write
【12】https://developers.google.com/web/tools/chrome-devtools/console/console-reference
【13】https://developer.apple.com/library/content/documentation/AppleApplications/Conceptual/Safari_
Developer_Guide/Console/Console.html
【14】https://developers.google.com/web/tools/chrome-devtools/inspect-styles/?utm_source=dcc&utm_medium=redirect&utm_campaign=2016q3
- 感謝您的閱讀,若有不足之處,歡迎指教,共同學習、共同進步。
- 部落客網址:http://www.cnblogs.com/wangjiming/。
- 極少部分文章利用讀書、參考、引用、抄襲、複制和粘貼等多種方式整合而成的,大部分為原創。
- 如您喜歡,麻煩推薦一下;如您有新想法,歡迎提出,郵箱:[email protected]。
- 可以轉載該部落格,但必須著名部落格來源。