Debug JavaScript with firebug)

Source: Internet
Author: User
Tags exit in line editor
In this chapter, we will discuss the various tools provided by firebug to support Javascript development, debugging, overview, and testing. Here we will use a typical
Javascript use cases, and explains how to use firebug to implement these cases.

In this chapter, we will discuss the following topics:

  • Command Line API and its Functions
  • Console API
  • One-step JavaScript debugging
  • Insert condition or unconditional breakpoint
Command Line API

In Chapter 2nd "firebug window overview", we have seen how to use the command line. Here we will discuss some methods provided by the command line API (methods ). These methods will help us debug JavaScript. The following is a detailed description and usage:

$ (ID)

This method is similar to document. getelementbyid () in JavaScript (). It returns a single element of the specified ID.

The following HTML code is used to explain the $ (ID) method. Write the code in an HTML file and open it with Firefox.

Now, when we execute the following code in the firebug command line, we will see the following output window:

$("test_id")


$ (Selector)

This method returns an array composed of elements matching the specified CSS selector.

Tip

For more information about the CSS selector, refer to this link: http://www.w3.org/TR/css3-selectors

The following HTML code snippets are displayed on the DOM tree with four <input> HTML elements. We will use the $ (selector) method to select all four elements:

The following shows the output result after $ ('input') is executed in the firebug command line:

Tip

To execute code in a single command line of firebug, you need to remove the "larger command line" option from the "console" tab drop-down menu.

$ X (XPath)

This method returns an array of elements that match the given XPath expression.

Tip

For more information about XPath, see: http://www.w3schools.com/xpath

To illustrate this method, we will use the preceding HTML file for explanation. Now, when we execute the following code in the firebug command line, we will see the output result on the firebug console tab:

        var objs = $x('html/body/input')        console.log(objs[0].name)        console.log(objs[1].name)        console.log(objs[3].name)        console.log(objs[3].name)


Note

Multi-line command line: for convenience, firebug provides a multi-line command line editor. This is a mini editor where we can enter multiple lines of JavaScript commands, or even complete javascript programs, and we can execute the code instantly. You can click the red icon in the lower-right corner of the console tab to open this multi-line editor.

Dir (object)

This method prints the interaction list of all attributes of the object. This result is consistent with what we see in the DOM tab.

Let's take a look at the HTML code we used in the $ (selector) method. If we execute the following code in the firebug command line, we will get the following output:

        var objs = $x('html/body/input')        dir(objs)


Dirxml (node)

This method prints the XML source code tree of an HTML or XML element. This result is consistent with the result we see in the HTML tab. We can click any node in the HTML tab to observe it.

Using the same HTML file, execute the following code in the firebug code line to obtain the XML source code tree. The output results in the console tab are shown below:

        var obj = $$('body')[0]        dirxml(obj)

We can use $ (ID) to select a node and pass it to this method, or use other methods like this to obtain a node.

By default, the command line expression is related to the top-level window of the page. The CD () method allows us to use the frame window in the page.

Clear ()

This method clears the console. You can also click the Clear button in the upper left corner of the console tab.

Inspect (object [, tabname])

This method allows us to use the most suitable label to check an object, or use the label consistent with the optional parameter tabname.

The tag names that can be used include HTML, CSS, script, and Dom.

Now, for the HTML document we have opened, enter the following code in the firebug command line. The output result is displayed in the HTML tab as follows:

        inspect($$('input')[0], 'html')


Keys (object)

This method returns an array containing the names of all attributes of this object.

Take the preceding HTML file as an example. Executing the following code will display all attributes, entities, functions, and constants of the first input Tag:

        keys($$('input')[0])


Values (object)

This method returns an array containing all attribute values of the object.

Execute the following code to display all attribute values of the first input tag in the DOM tree.

        values($$('input')[0])


Debug (FN) and undebug (FN)

The two methods will add or remove breakpoints in the first line of the function.

We will learn the details of these methods in chapter 8th "ajax development.

Monitor (function name) and unmonitor (function name)

These methods are used to enable or disable logging for all calls to a function.

Generally, to check whether a function in Javascript is called, we set the alert () or console. Log () method internally. This is a very tedious task. First, we have to find this method in a large Javascript file, and then we need to add the alert or log method. Next, when we see that everything is correct, we need to remove all these log declarations from the code.

Firebug uses a clever way to handle this monitoring job. To determine whether a function is called, we only need to know the function name. By using the Monitor () method, we can track how many times the function has been called. We will see a prompt on the console, telling us whether the function being monitored has been called. In addition, it will give us a link to the function script.

The following code is used as an example to create an HTML file, enter the following code, and open the file in Firefox:

        

Now, enter the following code in the command line and execute it:

        monitor(function1)

Click "INVOKE function1 ()" in this document ()". We will see that firebug will display its log records on the console panel whenever the function1 () function is called once. If you click the function1 () link on the console panel, the row where the function1 () function is located is displayed.

The following code unmonitors the function1 () function:

        unmonitor(function1)


Monitorevents (object [, Types])

This method enables logging of all events sent to an object. The optional parameter type specifies that only a specific message family is recorded. The most commonly used values are mouse and key.

All available types include composition, context menu, drag, focus, form, key, load, mouse, mutation, paint, scroll, text, UI, and XUL.

Unmonitorevents (object [, Types])

This method disables logging for all events sent to an object.

Monitoring and canceling monitoring events are the same as log events. We have discussed log events in the previous chapter.

Let's look at the fully-used HTML file. Execute the following code in the command line and click the first button:

        monitorEvents($("button1"))

The following shows the event monitoring status:

Profile ([title]) and profileend ()

These two methods are used to enable and disable the Javascript er. The optional parameter title is printed as the title of the overview report in the text.

The following are three methods for starting the Javascript profile in firebug:

  • On the console tab, click "Overview ".
  • Use console. Profile ("profiler title") from JavaScript code ")
  • Use profile ("profiler title") from the command line ")

To view the statistical information generated by the overview tool, enter the following HTML code, save it as an HTML file, and open the file in the browser. Press F12 to open firebug and click "start.

        

The following shows the statistics generated by the overview tool:

Topic and description of the overview Tool
  • Function): The name of each function is displayed in this column.
  • Call): The number of times this function is called. (In this example, the loop () function is called three times .)
  • Percentage (percent): This column shows the percentage of time consumed by each function.
  • Time used (own time): The time occupied by the code in a function is displayed in this column. For example, Foo () does not have its own code. Instead, it only calls other functions. Therefore, the execution time is approximately ~ 0 ms. If you look at some values in this column, we will add some loops in this function.
  • Time): This column shows the time taken to execute the function from the start point to the end point. For example, Foo () has no code. Therefore, the execution time is about ~ 0 ms, but other functions need to be called in this function. Therefore, the entire execution time of other functions is 4.491 milliseconds. As a result, 4.54 MS is displayed, which is the sum of the execution time of the Three loop () functions plus the execution time of its own Foo () function.
  • Average time (avg): This column displays the average execution time of a function. If we call this function only once, we will not see the difference. However, if this function is called multiple times, we will see the difference. The calculation formula is as follows:

    Average time = code execution time/number of calls

  • Min and Max Columns): The minimum execution time of the function is displayed here. In our example, we call loop () three times. When we pass 1000 as the parameter, it only takes a short time (0.045 seconds). When we pass 100000 to this function, it takes a longer time (4.036 seconds ). Therefore, in this example, the minimum time is 0.045 seconds, and the maximum time is 4.036 seconds.
  • File): This column displays the name of the file where the function is located and the number of rows.
Console API

Firebug adds a global variable to all loaded pages, named "console ". This object includes many methods that allow us to write information to the console to reveal information about script running.

Console. Log (object [, objcet,...])

This method writes a message to the console. We can pass any number of parameters that are linked in a space-separated row.

The first log parameter may contain a string similar to the printf string replacement mode. For example:

                console.log("The %s jumped over %d tall buildings", animal, count);

The above example can be rewritten with a non-string replacement method, with the same effect:

                console.log("The", animal, "jumped over", count, "tall buildings");

These two technologies can be used together. If we use the string replacement mode, but the given parameters are more than the parameters used in the replacement mode, the remaining parameters will be appended to the space separation line, as shown in the following code:

        console.log("I am %s and I have:", myName, thing1, thing2, thing3);

If the object is logged, these objects are displayed not only static text, but also interactive hyperlinks, these links point to the HTML, CSS, script, or DOM tab related to the object in firebug. We can also use the % o mode to replace hyperlinks in strings.

Below are all the modes that can be replaced by strings:

Table 1. 1.

String

Replacement Mode

% S

String

% D, % I

INTEGER (formatted values are not supported)

% F

Floating Point Number (formatted numeric value not supported)

% O

Object Link

Console. debug (object [, object,...])

This method writes a message to the console, which includes a hyperlink pointing to the row called by this method.

Console.info (object [, object,...])

This method writes a message to the console, which contains a visual info icon, color code, and a hyperlink to the row called by this method.

Console. Warn (object [, object,...])

This method writes a message to the console with a visual warning icon, color code, and a hyperlink pointing to the row called by this method.

Console. Error (object [, object,...])

This method writes a message to the console with a visualized error icon, color code, and a hyperlink pointing to the row called by this method.

Console. Assert (expression [, object,...])

This method tests whether an expression is true. If not, it writes a message to the console and throws an exception.

Console. dir (object)

This method prints an interactive list of all attributes of an object. It looks like the view we see on the DOM tab.

Console. dirxml (node)

This method prints the XML source code tree of HTML or XML elements. This is consistent with what we see on the HTML tab. You can click a node to check the node in the HTML tab.

Console. Trace ()

This method outputs the tracking of the interactive stack executed by the JavaScript code when it is called.

This stack trace lists the function details in the stack and each parameter value passed to the function. Click the function to go to the corresponding code location on the script tab. In addition, you can click the parameter value to view its information on the Dom or HTML tab.

Console. Group (object [, object,...])

In this method, you want to write a message to the console, and all messages written to the console will be indented and embedded into a block. You can call console. groupend () to disable this block.

Console. groupcollapsed (object [, object,...])

This method is similar to console. Group (), but the block is initially collapsed.

Console. groupend ()

This method is used to close the block recently opened by console. Group () or console. groupend.

Console. Time (name)

This method creates a timer with the given name. Call console. timeend with the same name to stop the timer and print the consumed time.

Console. timeend (name)

This method terminates the timer created by console. Time (name) and prints the consumed time.

Console. Profile ([title])

This method enables the Javascript almost writer. Optional parameters will appear in the header of the overview report.

Console. profileend ()

This method will close the Javascript overwrite and print out the report.

Console. Count ([title])

This method returns the execution time of the code line called by count. As the title of an optional parameter, a message output is added to the row where count is located.

Note

The console is an object appended to the window object on the web page. In firebug, this object is only attached when the console is enabled. In firebug lite, if lite has been installed on this page, the console will be attached.

Javascript debugging

This section describes how to use firebug to debug JavaScript both internally and externally. Before you start, review the content described in the previous chapter:

  • Script Tab
  • Command Line API
  • Console API

Using Mozilla Firefox and firebug to debug Javascript is a very intuitive process. If we are a developer of Visual Studio, we will not feel any difference in using firebug to debug JavaScript except that the debugger is part of the browser.

Single-step JavaScript debugging in firebug

Enter the following code in an editor and save it as a. html file. Then open it with Firefox:

Press F12 in the browser to open and activate firebug. Click the "script" tab and insert the breakpoint in line 6th, as shown in the following figure:

Note

To verify that a breakpoint has been inserted, you can view the breakpoint list in the "breakpoint" Panel on the right of the script tab.

A large red dot is displayed in row 6th, indicating that a breakpoint is inserted here. Now, click "Click me !" Button to execute JavaScript code.

Once we click, JavaScript will stop at line 1, where the breakpoint is located.

Now we can debug Javascript in one step and click these buttons on the script tab to continue, step by step, skip by step, and exit by step.

  • Continue (F8): as long as the script execution is terminated by another breakpoint, this button allows us to continue the script execution.
  • Single Step-in (F11): This button allows us to step into another function.
  • Single-step SKIP (F10): This button allows us to skip function calls in one step.
  • Exit in one step: This button enables us to continue script execution and stop at the next breakpoint.

Now, we click "Skip in one step" and press F10 to execute the 6th rows and move them to the 7th rows. Pay attention to the divelement value in the "monitoring" Panel on the right. The value is undefined before the execution of row 6th. After the execution of row 6th, it is assigned an HTML Div element as the value. Let's look at the following:

To view the stack of the call and execution stream, click the "stack" tab on the right of the script tab.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.