Make Your First Web App Amazing With These 10 Core Web APIs


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.

1

Access 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 or adding small, dynamic enhancements to their site.

Related


What Does An Interface Do in Object-Oriented Programming?

One of the key components of Object-oriented languages like Java and C# is the ability to write classes using interfaces, which standardize method definitions and enable enhanced polymorphism.

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.

The DOM (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.

A class diagram showing that the HTMLParagraphElement inherits from HTMLElement which, in turn, inherits from Element, which inherits from Node.

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:

        document.querySelectorAll("p").forEach(function(element) {
    element.style.color = "orange";
});

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.

2

Create 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. The URL API includes convenient methods to work with URLs.

URL support used to be patchy in JavaScript web programming, but the URL API made it much easier.

        let addr = new URL("https://example.com/this/is/just?an=example");
console.log(addr.pathname);
console.log(addr.searchParams.get("an"));

Parsing a URL, via the Window.URL() constructor, returns an object with properties representing different parts of that URL. These include things like hash for the fragment identifier, host for the URL’s domain and port, and searchParams which gives access to query parameters.

3

Fetch Web Content

Whether you’re processing the href values of links on a page, or managing URLs for remote services, Fetch is an easy, helpful resource. The Fetch API lets 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:

        fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(response => response.json())
    .then(json => console.log(json))

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.

4

Inspect and Modify the Browser’s Navigation History

Much of the work involved when creating web apps involves tackling the restrictions imposed by HTTP. 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:

        <button id="b" data-page="page2.html">Page 2button>

You can then add an entry to the browser history when this button press causes the page contents to update:

        button.addEventListener("click", function(ev) {
    let page = ev.target.getAttribute("data-page"),
        data = fetch_page(page);

    history.pushState(data, "", page);
});

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.

5

Replace 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:

        localStorage.setItem("Theme", "Dark");
...
let theme = localStorage.getItem("Theme");

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 can convert them to JSON using JSON.stringify() before you save them, then call JSON.parse() on load.

6

Discover 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:

        navigator.geolocation.getCurrentPosition(success, error);

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.

7

Read and Write Files on Local Disk

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.

        async function getFile() {
    const [fileHandle] = await window.showOpenFilePicker();
    const file = await fileHandle.getFile();
    console.log(file.name + " is a " + file.type);
    return file;
}

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.

8

Serve 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.

Related


These 5 Android Notification Features Will Make Your Day Easier

Notifications made simple and effective.

Web apps are catching up, though. You may have seen web apps offering their own notifications, and these are enabled by the Notifications API.

There are several stages to the notification workflow, starting with requesting permission:

        Notification.requestPermission().then((result) => {
    console.log(result);
});

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:

        new Notification("Do something important!");

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.

9

Draw to the Screen Using Canvas

The Canvas API provides 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:

        <canvas id="c">canvas>

With this element in place, it’s easy to draw a rectangle:

        document.getElementById("c").getContext("2d").fillRect(10, 10, 100, 60);

The full API has support for many different shapes, colors, and styles. It lets you draw text, transform images, and even create complex animations.

Related


I Tried Coding a Game With ChatGPT, Here’s How It Went

Coding a game is a lot of work, but can ChatGPT make it easier? The truth is, you’ll still need to know how to code.

10

Support Connected Gamepad Controllers

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:

        requestAnimationFrame(updateStatus);

function updateStatus() {
    let gamepad = navigator.getGamepads()[0];
    const GAMEPAD_BUTTON_LEFT = 14;

    if (gamepad) {
        gamepad.buttons.entries().forEach(function (btn) {
            if (btn[0] === GAMEPAD_BUTTON_LEFT && btn[1].pressed) {
                console.log("LEFT is pressed");
            }
        });
    }

    requestAnimationFrame(updateStatus);
}

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.

Related


The Perfect Gaming Controller Came Out in 2021, Here’s Why I Still Love It

It connects to everything and can stand the test of time.


These Web APIs—and many more—are documented 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.



Source link