Things I didn’t Know about Chrome DevTools

Posted on

I have been using Firebug as my debugging tool since I started web development. Firebug has been very helpful and the one thing I knew Chrome DevTools has that Firebug doesn’t is performance profiling which helps finding signs of memory leaks on a web page. I have wanted to take the free course Explore and Master Chrome DevTools for a while and I finally cross it out of my to-do list. It took me about four hours to complete the course and I have learned a few cool features of Chrome DevTools that I didn’t know about.

Explore and Master DevTools

  • Ways of get a DOM node
    Besides using the magnifier to select the DOM node on the web page, you can use the jQuery style of getting the DOM node with “$” sign. For example, $(“#name”) will give you the DOM node with id as name. If you select a DOM node in the Elements tab, you can then type in “$0″ in the Console tab to get the DOM node. On the other hand, you can type “inspect($0)” in the Console tab to show the DOM node in the Element tab.
  • Show style for different states
    lunapic_136720788190059_6There is a Toggle Element States option in the Elements -> Styles tab which will open the section for you to set the element state to active, focus, hover, and visited. I found this very helpful to debug the style issue for these states as the style definitions won’t be shown in the Styles tab unless they are in that state.
  • Dynamical editing source files and data source and view the change history
    You can edit CSS files or JavaScript files under the Sources tab. Right click in the file, you will see the option “Local modifications…” to see the change history and revert them. While we are used to editing CSS files, dynamically being able to update JavaScript is very useful.
  • Save updated file locally
    The changes were saved in the Chrome local storage if you edit them in the Sources tab and you can also save the updated files in your computer and override the original ones.
  • Events/Frames view in Timeline
    Frames view in Timeline
    The Timeline tab provides three types of views for the recording: Events, Frames, and Memory. The Events/Frames view shows the time spent on HTML parsing(blue), JavaScript rendering(yellow), style calculation(purple), and CSS rendering(green). The memory view is for detecting the sign of memory leaks.
  • Other plugins
    Page speed: It’s similar to YSlow. It gives you the suggestions of improving performance. After it’s installed, it’s will be shown as a new tab in the devTools.
    Google Closure: Compress multiple JavaScript files into one to reduce the number of HTTP requests.

Above are just new things that I learned in the class and I enjoyed taking this interactive class. Visit this link for more details about how to improve the performance of your application with Chrome DevTools.


Google APIs

Posted on

I have been thinking what I should write about for a while. Believe it or not, even though I have two weeks off from work during this holiday season, I still want to do what I do at work – building applications. This blog post is about Google APIs, specifically the Books API with which I built a simple book search application. While there are a lot of APIs available out there, Google APIs is pretty cool to try out.

Currently, there are 55 available APIs on Google APIs Console including Analytics API, Drive API, and YouTube Analytics API. Most APIs have request limits for free usage but some of them are available only with pricing plan such as Google Cloud SQL and Google Maps Geolocation API. The usage of API access is tracked by the API key generated on the website and you can view the quotas and report as well.

Google Books API allows you to perform CRUD operations on Google Books database with the proper authorization. The search scope can be the whole database or specific users’ both custom and pre-defined bookshelves like books they marked as favorites or read. Operations to retrieve user private data require OAuth token which can be easily generated on the Google API access page. The book concepts are easy to understand except that a book is given a term “volume” in the API.

For the coding part, you will need to request a script from Google API website.

//load script to access Google API
<script src="https://apis.google.com/js/client.js?onload=onLoadCallback"> </script>

Once the script is loaded, you can configure the client object for the query request that you are making.

function onLoadCallback(){
   var _this = this;
   //in this example, the param for API is "books" and the param for API version is 'v1' 
   this.client.load('books', 'v1', function (data) {
      //specify your API key       
      _this.client.setApiKey("{Your API key}");
   });
}

Now you can send any search requests with different parameters. The parameter “fields” defines the data fields to be returned. It’s important because without it, a large object with the complete information of books will be returned. You will never need so much information for your application and it would decrease the performance significantly.

var params = {
          //fields to return. return full information by default.
          fields:"items(volumeInfo/title, volumeInfo/authors,volumeInfo/publishedDate, 
                  volumeInfo/description, volumeInfo/imageLinks/thumbnail)",
          //maximum number of results to return. 10 by default
          maxResults:15,
          //sorting method. "relevance" by default
          orderBy:"newest"
    },
    restRequest = this.client.request({
          //specify the query request. 
          //the path below will return maximum number of 15 books 
          //with information matching "javascript" ordered by the most recent published date
          path:"/books/v1/volumes?q=javascript" + "&fields=" + params.fields 
               + "&maxResults=" + params.maxResults + "&orderBy=" + params.orderBy
    });

//sent the request
restRequest.execute(function (resp) {
   //use the return data 
});

With the proper data, you can build so many amazing applications. Google Books API is one of the easy-to-use APIs that I have used but there are a lot more features that I want to add to my Book Search with Google Books API application. If I ever run out of ideas for blogging, that’s what I am going to do :)


Survey Form with Validation

Posted on

Form is one of the key elements of a web application. It enables the communication and interaction between the users and a website. However, it is also a major channel of attacking a web site as I mentioned in my earlier blog post Web Application Security. Although it is not enough to secure a website by validating and sanitizing user input in the front-end, validation for a form can detect unintentional human mistakes and reduce invalid calls to the server. In this blog post, I will explain a few form validation methods using dojo form widgets.

The most common web forms are for managing a user account, leaving a message or conducting a survey. In this post, we will use a survey form for example. Let’s take a look at the form below and spend a few minutes to think about how you can validate the user input in different specific fields.

a blank form

Since a valid name only include letters, spaces, and sometimes dash, the validation can be done by a simple regexp expression and specify it with the regExp property of the ValidationTextBox. ValidationTextBox checks user input as they type and show error message if needed.

// code for name input field
<label for="name">Name*: </label>
  <input id="name" type="text" name="name" 
         data-dojo-type="dijit.form.ValidationTextBox"
         data-dojo-props="regExp:'^[- A-Za-z]+$',
         required:true, trim:'true', maxlength:64"/>

Age input field is a drop down menu which is good for security as well as usability. It provides options for user to choose from and the options can be only those interested ones. Since the value for each option is set, nothing much needs to be done in the front-end. The value of form does not contain most of the advanced form widgets and this rating widgets is one of them, thus you will need to get the values for those fields individually and mix in with the rest of the form data when submitting the form.

Besides using regexp to validate the input, you can take advantage of the predefined validate functions in dojox/validate.

// code for email input field
<label for="email">Email*: </label>
<input id="email" type="text" name="email" data-dojo-attach-point="email" 
    data-dojo-type="dijit.form.ValidationTextBox"
    data-dojo-props="required:true, invalidMessage:'Invalid Email address', 
    trim:'true', maxLength:32"/>

The rating field is one of dojox form widgets where you can specify number of stars and default value. Same with other textbox input, I used a customized regexp to validate the reference # field. SimpleTextArea widget lets you specify the rows and cols for the text area while TextArea widget will display a text box and change the size as the user types in more data.

// set validator for reference # field
_setValidator: function _setValidator(){
    this.refNum.validator = function(value){
        return value== "" || /^[s-zS-Z][a-hA-H][0-9]{6}$/.test(value);
    };
}

// strip off invalid characters in textarea
_cleanString: function _cleanString(text){
    return text.match(/[^<>\\]?/g).join("");
}

Last but not least, connecting events with the submit button.

on(this.submitBtn, "click", lang.hitch(this, function(){
    var rating = this.rating.get("value"),
	    commentText = this._cleanString(this.comment.value);

    if(this.form.validate() && rating !== 0){
        response = "Form data in json format:<br/>";
        response += json.stringify(lang.mixin(this.form.get("value"), 
            {comment:commentText, rating:rating}));
    }
    else{
        response = "Form can not be submitted.<br/>";
        response += "Please fill in all required field and verify the data 
            you have entered.";
    }
    this.formDataDiv.innerHTML = response;
}));

Check out the Demo.