In this two part tutorial series, we'll take a look at writing & debugging JavaScript code using modern tooling such as the Chrome DevTools.
In part 1, you'll get a introductory look at the various panels in the DevTools and what workflows they're suitable for. There'll also be a focus on writing and executing JavaScript code through the browser rather than a code editor.
Developer Tools are features provided by browsers containing a set of utilities to inspect, interact with and debug web pages. Browser DevTools are typically bundled with all modern browsers including Chrome, Firefox, Safari, Opera, and Internet Explorer. This tutorial will focus specifically on the DevTools part of Chrome Canary, but all features listed here are likely to be part of Chrome Stable soon.
The open web platform enables you to Right-Click > Inspect Element on any web page and discover the internals of it, but JavaScript has always been a bit more out of reach than CSS (Cascading Style Sheets). While DevTools is packed with features related to the styling of the page, there is also a heap of lesser-known functionality which enables you to view, write and debug JavaScript in a variety of ways, whether it’s on your own page or on a third-party site.
If you are a front-end web developer, it’s recommended you at least be aware of the JavaScript utilities DevTools has to offer. High-level features include:
This section will cover the UI elements of the DevTools, specifically the Sources Panel and the Console Panel, since these are the two panels which will be used for the rest of this tutorial.
Take note of a few layout characteristics:
The Sources Panel provides you with a code editor, and it supports syntax highlighting for many common file formats such as HTML, CSS, JavaScript, CoffeeScript, LESS, and Sass. The code editor is present within the main pane. Directly above the main pane you can see tabs corresponding to your open files.
In the Sources Pane within the left sidebar there is a file tree typically showing the assets the currently inspected page has loaded. Assets are grouped by domain, and folders can be in an expanded or collapsed state. If you single-click an asset, it will open up in the code editor.
The right sidebar contains controls for JavaScript debugging, and each pane can be in an expanded or collapsed state. Various levels of output are displayed here when JavaScript is paused at a breakpoint.
The Console Panel enables you to view the output produced by diagnostic logging (such as console.log
statements) but also to write and evaluate JavaScript within the context of the currently inspected page. The Console Panel supports both the Console API and the Command Line API. Here are some functions exposed by each API, along with a description of their output.
//A simple log statement, logging a string, array and an object console.log('Hi', [1,2,3], this);
//Same as console.log but formatted in red to signify an error console.error('An error occurred');
keys(window); //Get the properties of an object
$0; //Retrieve the currently selected element in the Elements Panel
The top of the Console Panel contains a few controls as shown below.
clear()
, which is part of the Command Line API.The Console Panel is one of the few panels which you can overlay over other panels in the DevTools (Elements, Network, Sources) to provide an improved workflow. If you find yourself regularly returning to the Console Panel, bring up the Console Drawer by pressing the Escape key.
This section will focus on using the DevTools to see JavaScript resources a site is using. Before continuing, it is recommended you disable the browser cache via DevTools. To do this, navigate to Settings > General and enable the checkbox titled Disable cache (while DevTools is open). This ensures you are always getting a fresh version of an asset.
Navigate to HTML5Please.com, a site explaining the readiness of Web Platform features. Open up the DevTools using Command-Shift-I or by selecting Inspect Element from the page context menu. Head on over to the Sources Panel and take note of the file tree structure shown in the left sidebar. It's not unheard of for websites to store their JavaScript in folders such as "js" or "scripts", so you already know where to look. Open up the script.js
file in the js
folder. Notice a few features of the code editor which can prove useful when you view or edit JavaScript code:
Use the go-to definition feature to quickly find or discover JavaScript methods or functions. You can open the go-to definition modal window via the shortcut Command-Shift-P. If you know the name of the method or function you are looking for, type it in the go-to definition search box; as you type, results will update in real time. Each result contains the matching method name (if there is one) and the line number where it is defined. Use Enter to select a search result, and you then land on the line of code where the function is defined.
Now open modernizr-2.0.min.js
in the js/libs
folder. The fact that this file is minified makes it harder to view. Select Pretty Print to have DevTools apply a more intuitive formatting to the file, using line breaks and indentation. The Pretty Print feature works for both CSS and JavaScript.
Each JavaScript file in the file tree has a context menu, so open it up using right-click. Notice a few options useful for taking the file offline for later use.
The Network Panel, in addition to simply showing you what resources a page has loaded, will also display other information and data.
Using HTML5Please.com as an example website, follow along with the steps below:
The first script, modernizr-2.0.min.js
, has the value of html5please.com/:17
for the initiator. This suggests it was an HTML resource which initiated the download of the script (rather than a script loader, for example). Click on the initiator, and you are taken to the line of code in the Sources Panel which references the file:
<script src="js/libs/modernizr-2.0.min.js"></script>
In the event that a script is dynamically inserted (with a script loader for example), the initiator column in the Network Panel can provide a JavaScript call stack relating to the calls which occurred all the way up to the point where the script was dynamically inserted into the DOM.
You can click on each call within a call stack to navigate to the relevant portion of code in the Sources Panel.
In the section "Viewing JavaScript using the DevTools", I explained how to view information, metadata, and source code on JavaScript assets. This section will examine the ways you can write JavaScript using the DevTools.
Use the Console Panel for writing quick JavaScript one-liners with immediate results. JavaScript is executed with the context of the currently inspected page. Execute some JavaScript in the Console Panel by pressing Enter after entering some code.
Refer to the Console API and Command Line API for a list of available methods and functions.
While the Console Panel is relatively simple, there are a few small tips to improve your workflow:
keys(window)
to detect global variables on the current page.$_
helper to retrieve the last result of a previous command.You may find the Console Panel to be a good candidate for quickly experimenting with JavaScript to discover what the output of certain expressions are. However, when you start writing more complex JavaScript, you can easily encounter limitations:
The Console Panel does not intend to be a code editor replacement or even alternative. Here is a list of some cases where the Console Panel can be useful:
call()
and apply()
methods by executing them inline and observing the resultsThe main pane of the Sources Panel contains a code editor with basic editing capabilities.
The editor itself is powered by CodeMirror, a powerful text editor implemented using JavaScript. DevTools imports the CodeMirror editor into its own codebase and selectively enables various features which are in turn made available to any Chrome user.
When editing JavaScript (amongst other supported languages), the Sources Panel editor contains a number of utilities such as:
document
is not suggested after typing in docu
unless there is already at least one occurrence of the word document
in the same file.The feature, better known as Live Edit, gives you the ability to edit a page's JavaScript code via DevTools and have the changes apply to the page immediately without a page refresh. There is no particular UI to use this; you simply rewrite a part of JavaScript code and press Command-S to save it.
How this works behind the scenes is explained below, but first, consider the following prerequisites (these are independant of Live Edit):
script.js
loads into Chrome via a web page.script.js
is parsed, evaluated, and compiled into machine code through the V8 JavaScript Engine.Here's what happens behind the scenes of the Live Edit feature, considering the previous points:
script.js
in the DevTools code editor. Assume there is a button on current web page. On button click, a click event listener executes an anonymous function.console.log
statement and save the file.script.js
are injected back into the V8 engine for processing.script.js
and the old one. Deletions, additions and modifications are stored.script.js
with the compiled changes.Live Edit works best with minor modifications rather than authoring entire JavaScript files for your app. Debug scenarios work well with Live Edit.
Workspaces is not a critical component of JavaScript debugging via the DevTools. However, depending on your requirements, it can speed up your debugging workflow. Workspaces is a feature of the DevTools which enables you to modify the contents of a folder on the file system by making code changes in the DevTools.
If you are browsing a project which is served locally though a web server, such as at http://localhost:3000/
and the project exists on your file system at ~/development/project
, for example, you can teach DevTools about the mapping between the two and use the Live Edit capabilities with save-to-disk abilities. Workspaces enables the following workflow:
In step 3, the save overwrites the original source file.
Source Maps solve a common problem when dealing with source code that is processed or compiled into something else. Examples include:
The problem is as follows: when debugging a processed version of the code, it can be hard to understand how your original source code maps onto what you are viewing during debugging. If you are getting an error in the DevTools console for a production website, you will typically end up having to debug a minified and concatenated version of JavaScript code, which bears little resemblance to the source files which you author.
A Source Map is a generated file produced as part of a compilation process which is available for the use cases listed earlier. DevTools can read a Source Map file to understand how a compiled file maps onto the original file.
The two code snippets (Source File—app.js and Transpiled file—compiled.js) demonstrate Source Map debugger-friendly code.
Example 1. Source File—app.js
for (var element of [1, 2, 3]) { console.log(element); }
Note that the app.js
source file uses an Ecmascript 6 compatible feature known as the Array iterator.
Example 2. Transpiled File—compiled.js
"use strict"; for (var $__0 = [1, 2, 3][Symbol.iterator](), $__1; !($__1 = $__0.next()).done; ) { var element = $__1.value; { console.log(element); } } //# sourceMappingURL=app.js.map
Note that compiled.js
is referenced by a script tag on an HTML page, along with the Traceur runtime, and finally is opened in a browser.
Even the compiled JavaScript has the console.log
statement on line 6. DevTools is able to show exactly where theconsole.log
statement exists within the original source file (Source Map debugging), which is on line 2. Breakpoints work as expected. Behind the scenes, the compiled JavaScript is evaluated and executed, but DevTools is presenting a different asset in lieu of the browser evaluated version.
The Snippets feature of the DevTools provides a quick way to write miscellaneous JavaScript code and execute it. All JavaScript executed via Snippets is run within the context of the current page. Executing a DevTools Snippet is similar to running a Bookmarklet on a page. You may find it preferable to write certain JavaScript within Snippets as opposed to the Console Panel for reasons related to a better code editing environment. Your snippets are saved within the Local Storage of the DevTools.
To use Snippets:
console.log('Hello');
in the code editor.You can find a number of already-written snippets in this DevTools Snippets repository.
That's it for Part 1 of a Modern Debugging Experience. In Part 2, we'll take a look at some debugging features and also a few extensions which can help with this.
The Best Small Business Web Designs by DesignRush
/Create Modern Vue Apps Using Create-Vue and Vite
/Pros and Cons of Using WordPress
/How to Fix the “There Has Been a Critical Error in Your Website” Error in WordPress
/How To Fix The “There Has Been A Critical Error in Your Website” Error in WordPress
/How to Create a Privacy Policy Page in WordPress
/How Long Does It Take to Learn JavaScript?
/The Best Way to Deep Copy an Object in JavaScript
/Adding and Removing Elements From Arrays in JavaScript
/Create a JavaScript AJAX Post Request: With and Without jQuery
/5 Real-Life Uses for the JavaScript reduce() Method
/How to Enable or Disable a Button With JavaScript: jQuery vs. Vanilla
/How to Enable or Disable a Button With JavaScript: jQuery vs Vanilla
/Confirm Yes or No With JavaScript
/How to Change the URL in JavaScript: Redirecting
/15+ Best WordPress Twitter Widgets
/27 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/21 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/30 HTML Best Practices for Beginners
/31 Best WordPress Calendar Plugins and Widgets (With 5 Free Plugins)
/25 Ridiculously Impressive HTML5 Canvas Experiments
/How to Implement Email Verification for New Members
/How to Create a Simple Web-Based Chat Application
/30 Popular WordPress User Interface Elements
/Top 18 Best Practices for Writing Super Readable Code
/Best Affiliate WooCommerce Plugins Compared
/18 Best WordPress Star Rating Plugins
/10+ Best WordPress Twitter Widgets
/20+ Best WordPress Booking and Reservation Plugins
/Working With Tables in React: Part Two
/Best CSS Animations and Effects on CodeCanyon
/30 CSS Best Practices for Beginners
/How to Create a Custom WordPress Plugin From Scratch
/10 Best Responsive HTML5 Sliders for Images and Text… and 3 Free Options
/16 Best Tab and Accordion Widget Plugins for WordPress
/18 Best WordPress Membership Plugins and 5 Free Plugins
/25 Best WooCommerce Plugins for Products, Pricing, Payments and More
/10 Best WordPress Twitter Widgets
1 /12 Best Contact Form PHP Scripts for 2020
/20 Popular WordPress User Interface Elements
/10 Best WordPress Star Rating Plugins
/12 Best CSS Animations on CodeCanyon
/12 Best WordPress Booking and Reservation Plugins
/20 Best WordPress Calendar Plugins and Widgets
/12 Elegant CSS Pricing Tables for Your Latest Web Project
/24 Best WordPress Form Plugins for 2020
/14 Best PHP Event Calendar and Booking Scripts
/Create a Blog for Each Category or Department in Your WooCommerce Store
/8 Best WordPress Booking and Reservation Plugins
/Best Exit Popups for WordPress Compared
/Best Exit Popups for WordPress Compared
/11 Best Tab & Accordion WordPress Widgets & Plugins
/12 Best Tab & Accordion WordPress Widgets & Plugins
1New Course: Practical React Fundamentals
/Short Course: Better Angular App Architecture With Modules
/Preview Our New Course on Angular Material
/Build Your Own CAPTCHA and Contact Form in PHP
/Object-Oriented PHP With Classes and Objects
/Best Practices for ARIA Implementation
/Accessible Apps: Barriers to Access and Getting Started With Accessibility
/Dramatically Speed Up Your React Front-End App Using Lazy Loading
/15 Best Modern JavaScript Admin Templates for React, Angular, and Vue.js
/15 Best Modern JavaScript Admin Templates for React, Angular and Vue.js
/19 Best JavaScript Admin Templates for React, Angular, and Vue.js
/New Course: Build an App With JavaScript and the MEAN Stack
/Hands-on With ARIA: Accessibility Recipes for Web Apps
/10 Best WordPress Facebook Widgets
13 /Hands-on With ARIA: Accessibility for eCommerce
/New eBooks Available for Subscribers
/Hands-on With ARIA: Homepage Elements and Standard Navigation
/How Secure Are Your JavaScript Open-Source Dependencies?
/New Course: Secure Your WordPress Site With SSL
/Testing Components in React Using Jest and Enzyme
/Testing Components in React Using Jest: The Basics
/15 Best PHP Event Calendar and Booking Scripts
/Create Interactive Gradient Animations Using Granim.js
/How to Build Complex, Large-Scale Vue.js Apps With Vuex
1 /Examples of Dependency Injection in PHP With Symfony Components
/Set Up Routing in PHP Applications Using the Symfony Routing Component
1 /A Beginner’s Guide to Regular Expressions in JavaScript
/Introduction to Popmotion: Custom Animation Scrubber
/Introduction to Popmotion: Pointers and Physics
/New Course: Connect to a Database With Laravel’s Eloquent ORM
/How to Create a Custom Settings Panel in WooCommerce
/Building the DOM faster: speculative parsing, async, defer and preload
1 /20 Useful PHP Scripts Available on CodeCanyon
3 /How to Find and Fix Poor Page Load Times With Raygun
/Introduction to the Stimulus Framework
/Single-Page React Applications With the React-Router and React-Transition-Group Modules
/12 Best Contact Form PHP Scripts
1 /Getting Started With the Mojs Animation Library: The ShapeSwirl and Stagger Modules
/Getting Started With the Mojs Animation Library: The Shape Module
/Getting Started With the Mojs Animation Library: The HTML Module
/Project Management Considerations for Your WordPress Project
/8 Things That Make Jest the Best React Testing Framework
/Creating an Image Editor Using CamanJS: Layers, Blend Modes, and Events
/New Short Course: Code a Front-End App With GraphQL and React
/Creating an Image Editor Using CamanJS: Applying Basic Filters
/Creating an Image Editor Using CamanJS: Creating Custom Filters and Blend Modes
/Modern Web Scraping With BeautifulSoup and Selenium
/Challenge: Create a To-Do List in React
1 /Deploy PHP Web Applications Using Laravel Forge
/Getting Started With the Mojs Animation Library: The Burst Module
/10 Things Men Can Do to Support Women in Tech
/A Gentle Introduction to Higher-Order Components in React: Best Practices
/A Gentle Introduction to HOC in React: Learn by Example
/A Gentle Introduction to Higher-Order Components in React
/Creating Pretty Popup Messages Using SweetAlert2
/Creating Stylish and Responsive Progress Bars Using ProgressBar.js
/18 Best Contact Form PHP Scripts for 2022
/How to Make a Real-Time Sports Application Using Node.js
/Creating a Blogging App Using Angular & MongoDB: Delete Post
/Set Up an OAuth2 Server Using Passport in Laravel
/Creating a Blogging App Using Angular & MongoDB: Edit Post
/Creating a Blogging App Using Angular & MongoDB: Add Post
/Introduction to Mocking in Python
/Creating a Blogging App Using Angular & MongoDB: Show Post
/Creating a Blogging App Using Angular & MongoDB: Home
/Creating a Blogging App Using Angular & MongoDB: Login
/Creating Your First Angular App: Implement Routing
/Persisted WordPress Admin Notices: Part 4
/Creating Your First Angular App: Components, Part 2
/Persisted WordPress Admin Notices: Part 3
/Creating Your First Angular App: Components, Part 1
/How Laravel Broadcasting Works
/Persisted WordPress Admin Notices: Part 2
/Create Your First Angular App: Storing and Accessing Data
/Persisted WordPress Admin Notices: Part 1
/Error and Performance Monitoring for Web & Mobile Apps Using Raygun
/Using Luxon for Date and Time in JavaScript
7 /How to Create an Audio Oscillator With the Web Audio API
/How to Cache Using Redis in Django Applications
/20 Essential WordPress Utilities to Manage Your Site
/Introduction to API Calls With React and Axios
/Beginner’s Guide to Angular 4: HTTP
/Rapid Web Deployment for Laravel With GitHub, Linode, and RunCloud.io
/Beginners Guide to Angular 4: Routing
/Beginner’s Guide to Angular 4: Services
/Beginner’s Guide to Angular 4: Components
/Creating a Drop-Down Menu for Mobile Pages
/Introduction to Forms in Angular 4: Writing Custom Form Validators
/10 Best WordPress Booking & Reservation Plugins
/Getting Started With Redux: Connecting Redux With React
/Getting Started With Redux: Learn by Example
/Getting Started With Redux: Why Redux?
/Understanding Recursion With JavaScript
/How to Auto Update WordPress Salts
/How to Download Files in Python
/Eloquent Mutators and Accessors in Laravel
1 /10 Best HTML5 Sliders for Images and Text
/Creating a Task Manager App Using Ionic: Part 2
/Creating a Task Manager App Using Ionic: Part 1
/Introduction to Forms in Angular 4: Reactive Forms
/Introduction to Forms in Angular 4: Template-Driven Forms
/24 Essential WordPress Utilities to Manage Your Site
/25 Essential WordPress Utilities to Manage Your Site
/Get Rid of Bugs Quickly Using BugReplay
1 /Manipulating HTML5 Canvas Using Konva: Part 1, Getting Started
/10 Must-See Easy Digital Downloads Extensions for Your WordPress Site
22 Best WordPress Booking and Reservation Plugins
/Understanding ExpressJS Routing
/15 Best WordPress Star Rating Plugins
/Creating Your First Angular App: Basics
/Inheritance and Extending Objects With JavaScript
/Introduction to the CSS Grid Layout With Examples
1Performant Animations Using KUTE.js: Part 5, Easing Functions and Attributes
/Performant Animations Using KUTE.js: Part 4, Animating Text
/Performant Animations Using KUTE.js: Part 3, Animating SVG
/New Course: Code a Quiz App With Vue.js
/Performant Animations Using KUTE.js: Part 2, Animating CSS Properties
Performant Animations Using KUTE.js: Part 1, Getting Started
/10 Best Responsive HTML5 Sliders for Images and Text (Plus 3 Free Options)
/Single-Page Applications With ngRoute and ngAnimate in AngularJS
/Deferring Tasks in Laravel Using Queues
/Site Authentication in Node.js: User Signup and Login
/Working With Tables in React, Part Two
/Working With Tables in React, Part One
/How to Set Up a Scalable, E-Commerce-Ready WordPress Site Using ClusterCS
/New Course on WordPress Conditional Tags
/TypeScript for Beginners, Part 5: Generics
/Building With Vue.js 2 and Firebase
6 /Best Unique Bootstrap JavaScript Plugins
/Essential JavaScript Libraries and Frameworks You Should Know About
/Vue.js Crash Course: Create a Simple Blog Using Vue.js
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 5.5 API
/API Authentication With Node.js
/Beginner’s Guide to Angular: HTTP
/Beginner’s Guide to Angular: Routing
/Beginners Guide to Angular: Routing
/Beginner’s Guide to Angular: Services
/Beginner’s Guide to Angular: Components
/How to Create a Custom Authentication Guard in Laravel
/Learn Computer Science With JavaScript: Part 3, Loops
/Build Web Applications Using Node.js
/Learn Computer Science With JavaScript: Part 4, Functions
/Learn Computer Science With JavaScript: Part 2, Conditionals
/Create Interactive Charts Using Plotly.js, Part 5: Pie and Gauge Charts
/Create Interactive Charts Using Plotly.js, Part 4: Bubble and Dot Charts
/Create Interactive Charts Using Plotly.js, Part 3: Bar Charts
/Awesome JavaScript Libraries and Frameworks You Should Know About
/Create Interactive Charts Using Plotly.js, Part 2: Line Charts
/Bulk Import a CSV File Into MongoDB Using Mongoose With Node.js
/Getting Started With End-to-End Testing in Angular Using Protractor
/TypeScript for Beginners, Part 4: Classes
/Object-Oriented Programming With JavaScript
/Stateful vs. Stateless Functional Components in React
/Make Your JavaScript Code Robust With Flow
/Build a To-Do API With Node and Restify
/Testing Components in Angular Using Jasmine: Part 2, Services
/Testing Components in Angular Using Jasmine: Part 1
/Creating a Blogging App Using React, Part 6: Tags
/React Crash Course for Beginners, Part 3
/React Crash Course for Beginners, Part 2
/React Crash Course for Beginners, Part 1
/Set Up a React Environment, Part 4
1 /Set Up a React Environment, Part 3
/New Course: Get Started With Phoenix
/Set Up a React Environment, Part 2
/Set Up a React Environment, Part 1
/Command Line Basics and Useful Tricks With the Terminal
/How to Create a Real-Time Feed Using Phoenix and React
/Build a React App With a Laravel Back End: Part 2, React
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 9 API
/Creating a Blogging App Using React, Part 5: Profile Page
/Pagination in CodeIgniter: The Complete Guide
/JavaScript-Based Animations Using Anime.js, Part 4: Callbacks, Easings, and SVG
JavaScript-Based Animations Using Anime.js, Part 3: Values, Timeline, and Playback
/Learn to Code With JavaScript: Part 1, The Basics
/10 Elegant CSS Pricing Tables for Your Latest Web Project
/Getting Started With the Flux Architecture in React
/Getting Started With Matter.js: The Composites and Composite Modules
/Getting Started With Matter.js: The Engine and World Modules
/10 More Popular HTML5 Projects for You to Use and Study
/Understand the Basics of Laravel Middleware
/Iterating Fast With Django & Heroku
/Creating a Blogging App Using React, Part 4: Update & Delete Posts
Creating a jQuery Plugin for Long Shadow Design
/How to Register & Use Laravel Service Providers
2 /Unit Testing in React: Shallow vs. Static Testing
/Creating a Blogging App Using React, Part 3: Add & Display Post
/Creating a Blogging App Using React, Part 2: User Sign-Up
20Creating a Blogging App Using React, Part 1: User Sign-In
/9 More Popular HTML5 Projects for You to Use and Study
/Creating a Grocery List Manager Using Angular, Part 2: Managing Items
/9 Elegant CSS Pricing Tables for Your Latest Web Project
/Dynamic Page Templates in WordPress, Part 3
/Angular vs. React: 7 Key Features Compared
/Creating a Grocery List Manager Using Angular, Part 1: Add & Display Items
/New eBooks Available for Subscribers in June 2017
/Create Interactive Charts Using Plotly.js, Part 1: Getting Started
/The 5 Best IDEs for WordPress Development (And Why)
/33 Popular WordPress User Interface Elements
/New Course: How to Hack Your Own App
/How to Install Yii on Windows or a Mac
/What Is a JavaScript Operator?
/How to Register and Use Laravel Service Providers
/
waly Good blog post. I absolutely love this…