Using JavaScript, you can radically transform HTML documents, adding functionality to static web pages and even creating full-blown web applications. At its core, JavaScript can do anything that any other programming language can. However, beyond this, web browsers implement several web APIs that provide powerful support for various features.
1Access and Modify HTML With the DOM
All Web APIs (Application Programming Interface) supply code so that you don’t have to. They handle the intricate low-level details, allowing developers to focus on building their app oradding small, dynamic enhancementsto their site.
Many of these APIs target specific technologies such as touch-screen input or notifications. This first API, however, is fundamental to all web programming that involves a document, like a web page written in HTML.
TheDOM(Document Object Model) is a standard representation of a web page that JavaScript can use to inspect its contents or modify certain parts. It reflects the hierarchical nature of HTML, and deals with core concepts like nodes, elements, events, and text.
If you want to change some text on a web page, remove all paragraphs, or highlight spelling mistakes, the DOM will be at the heart of it. For example, here’s a short snippet that will change the color of every paragraph on a page:
The DOM provides the Document.querySelectorAll() method and the HTMLElement.style property. Respectively, they retrieve matching Elements and access inline CSS.
You can run this snippet on any website, using your browser’s developer tools feature. It’s a good way of checking how well-structured a web page is: if the things you expect to be paragraphs don’t turn orange, there may be errors in the HTML.
2Create and Manipulate URLs More Easily
Some Web APIs have a huge scope, but others are much more limited. This API is one of the latter. TheURL APIincludes convenient methods to work with URLs.
URL support used to be patchy in JavaScript web programming, but the URL API made it much easier.
Parsing a URL, via the Window.URL() constructor, returns an object with properties representing different parts of that URL. These include things likehashfor the fragment identifier,hostfor the URL’s domain and port, andsearchParamswhich gives access to query parameters.
3Fetch Web Content
Whether you’re processing thehrefvalues of links on a page, or managing URLs for remote services, Fetch is an easy, helpful resource. TheFetch APIlets you write code that acts a bit like a headless browser.
You can fetch remote content and inject it into a page, or fetch data and process it. If a site provides weather forecasts or stock market data, you can use Fetch to grab that data and integrate it with your own app.
A single method—Window.fetch()—provides all the functionality of the Fetch API. Here’s a simple example of how to use it:
If you run this in your browser’s console, it should print the details of the object you see if you go directly to https://jsonplaceholder.typicode.com/todos/1. Behind the scenes, the Fetch API sends a request to the target website and returns the response to the calling code, ready for further processing.
4Inspect and Modify the Browser’s Navigation History
Much of the work involved when creating web apps involves tackling the restrictions imposed byHTTP. The protocol was designed to cater to distinct documents, loaded and displayed via individual requests. JavaScript programming complicates things; in particular, web apps can pollute the browser’s history and can break the back button if you’re not careful.
To deal with these issues, the History API lets you navigate and modify the user’s history. The most practical use of this feature is to inject useful entries in the history that would otherwise go ignored. For example, you may have a button that updates your document using JavaScript:
you’re able to then add an entry to the browser history when this button press causes the page contents to update:
The pushState() method adds an entry to the browser’s history, complete with a record of data that you can retrieve if the user navigates back to this page. As a result, your web app can be much more responsive, avoiding unnecessary trips to the server, but still presenting useful navigation history.
5Replace Cookies With JavaScript-Accessible Storage
The old way of storing state across HTTP requests was to use cookies. These small packets of data were saved on the client and transmitted to the server in HTTP headers, but this meant JavaScript could not access them.
To support a similar mechanism for JavaScript, the Web Storage API lets you save data, either for the current session or permanently. It’s a simple key/value pair system:
This API is perfect for web apps that don’t need server functionality. You can easily upgrade a static website by storing user preferences or data about viewed pages.
The values you save using the Web Storage API must be strings. To store other types of data, you’re able to convert them to JSON using JSON.stringify() before you save them, then call JSON.parse() on load.
6Discover Where Your Users Are Using Geolocation
Historically, if you needed to work with a visitor’s physical location, you’d need a native app. The Geolocation API provides this functionality to web browsers, provided the user grants permission.
Location details can be used for many reasons: to show nearby stores, to provide location-specific content, or to determine a user’s timezone, for example. Working with the user’s location is as simple as calling the getCurrentPosition() method of the navigator.geolocation object:
You’ll need to define the error and success functions; the latter gets passed a GeolocationPosition object with a coords property. There are no bells and whistles here, so you’ll need to fetch information like country or timezone separately. But the coordinates you get back can be very accurate, and the API is straightforward to use.
Traditionally, web apps have not been able to access local files, for security reasons. This is a shame since it prevents a whole set of interesting apps, like paint programs, text editors, and so on. Fortunately, the File System API enables these uses.
You can use the resulting File object to read data from the file, directly from disk. Writing is a similar process, involving the showSaveFilePicker() method and the FileHandle’s createWritable() method.
Using the File System classes, reading and writing data is now largely transparent, enabling tighter integration with local disk storage. This API is one of the most important for bringing web apps into line with native applications.
8Serve Up Useful & Timely Notifications
Mobile apps have pioneered features that tell users about important events automatically. It’s useful when an app tells you about something so you don’t have to go looking for it yourself.
Web apps are catching up, though. You may have seen web apps offering their own notifications, and these are enabled by theNotifications API.
There are several stages to the notification workflow, starting with requesting permission:
This is a vital step that the API enforces since nobody wants websites creating notifications against their will. With permission, though, sending a notification is pretty easy:
If your browser settings allow, this will immediately show a notification. For a long-running web app, like a social media site, you might poll for new content intermittently, then create a notification if a matching post appears in the feed.
9Draw to the Screen Using Canvas
TheCanvas APIprovides low-level functions to draw graphics in a canvas element. You might use this to create dynamic images, build a game, or develop a full-fledged graphics app.
Start with a canvas element in your web page:
With this element in place, it’s easy to draw a rectangle:
The full API has support for many different shapes, colors, and styles. It lets you draw text, transform images, and even create complex animations.
Another API that you might be surprised to see: yes, web apps can support gamepads and other game controllers!
To detect button presses, you’ll need to use polling rather than event handling, and this can be less convenient. The standard approach is like this:
You’ll need to deal with button mappings, and this code can be quite complex, but it’s well worth it to add support for gamepads to your web-based games.
These Web APIs—and many more—aredocumented at MDN. The best way to learn about them is to try out sample code, like the above snippets. Experiment in your browser’s JavaScript console and discover new types of app you can build using just HTML, CSS, and JavaScript.