Wednesday, October 5, 2022
HomeWeb developmentJavaScript APIs You Don’t Know About — Smashing Journal

JavaScript APIs You Don’t Know About — Smashing Journal


A few days in the past, I revisited the superior 2021 State of JS Survey. The state of JS is a web-based survey that collects knowledge from builders all over the world to see the latest and upcoming tendencies within the JavaScript neighborhood. Among the many knowledge it collects, a bit is devoted to the native options JavaScript offers, listed by their utilization and consciousness. As you may think about, among the many most used options are fashionable ones like Optionally available chaining, Nullish coalescing, Websockets, and so forth.

Nonetheless, I wasn’t fascinated about probably the most used or identified APIs. As a substitute, I used to be in search of the least identified ones. I needed to know which APIs we aren’t speaking about sufficient, and amongst them, I discovered 4 fairly totally different APIs which can be extraordinarily helpful:

On this article, we’ll see what they’re, the place we should always use them, and how you can use them.

Notice: These APIs are all accessible on this demo.

Web page Visibility API

This can be a little-known net API that charges final fourth in consciousness within the State of JS Survey. It lets you realize when a consumer has left the web page. To be exact, the API triggers an occasion every time the web page visibility standing adjustments, both when the consumer minimizes or maximizes the window or switches the tab.

Previously, you had to make use of gimmicks to know if a consumer had switched tabs or minimized the window. The preferred was utilizing the blur and focus browser occasions. Utilizing these occasions would end in one thing like the next:

window.addEventListener("focus", perform () {
    // Consumer is again on the web page
    // Do One thing
});

window.addEventListener("blur", perform () {
    // Consumer left the web page
    // Do One thing
});

The earlier code works however not as supposed. Because the blur occasion is triggered when the web page loses focus, it may be triggered when the consumer clicks the search bar, an alert dialog, the console, or the window border. So, blur and focus solely inform us if the web page is lively however not if the content material of the web page is hidden or seen.

Use Instances

Normally, we wish to use the Web page Visibility API to cease pointless processes when the consumer doesn’t see the web page or, alternatively, to carry out background actions. Some particular instances may be:

  • to pause movies, picture carousels, or animations when the consumer leaves the web page;
  • if the web page shows reside knowledge from an API, cease this habits quickly whereas the consumer is away;
  • to ship consumer analytics.

How To Use It?

The Web page Visibility API brings two properties and an occasion to entry the web page visibility standing:

  • doc.hidden
    It’s globally accessible and read-only. Attempt to keep away from it since it’s now deprecated, however when accessed, it returns true if the web page is hidden and false whether it is seen.
  • doc.visibilityState
    It’s the up to date model of doc.hidden, however when accessed, it returns 4 attainable values relying on the web page visibility standing: – seen
    The web page is seen, or to be actual, it isn’t minimized nor in one other tab. – hidden
    The web page isn’t seen; it’s minimized or in one other tab. – prerender
    That is the preliminary state of a visual web page when it’s prerendering. A web page’s visibility standing could begin at prerender after which change to a different state, however it might probably’t change from one other state to prerender. – unloaded
    The web page is being unloaded from reminiscence.
  • visibilitychange
    It’s an occasion offered by the doc object that’s triggered when the web page visibilityState adjustments.
doc.addEventListener("visibilitychange", () => {
    if (doc.visibilityState === "seen") {
        // web page is seen
    } else {
        // web page is hidden
    }
});

To see how you can use the Web page Visibility API, let’s use it to pause a video and cease fetching sources from an API when the consumer leaves the web page. To begin, I will probably be utilizing vite.js, which is an incredible device to begin a brand new venture shortly:

npm create vite@newest unknown-web-apis

When requested to pick a framework, choose vanilla to create a vanilla javascript venture. And as soon as completed, go to the brand new folder, set up the mandatory npm packages and begin the developer server:

  cd unknown-web-apis
  npm set up
  npm run dev

Go to localhost:3000/, and you will note your Vite venture up and operating!

Vite New Project
Vite New Mission. (Giant preview)

Firstly, we’ll direct to the /primary.js file and delete all of the boilerplate. Secondly, we’ll open /index.html, and contained in the #app div tag, we’ll add a video ingredient with any video file you need. I used a dancing Yoshi one. 🙂

<div id="app">
    <video controls id="video">
        <supply src="https://smashingmagazine.com/2022/09/javascript-api-guide/./yoshi.mp4" />
    </video>
</div>
Video with controls showing a Yoshi image
Video with controls exhibiting a Yoshi picture. (Giant preview)

Again to /primary.js, we’ll add an occasion listener to the doc object listening to the visibilitychange occasion. We then can entry the doc.visibilityState property to see when the web page is seen or hidden.

doc.addEventListener("visibilitychange", () => {
    console.log(doc.visibilityState);
});

You possibly can go to the web page’s console and see the web page visibility standing change while you reduce the window or swap to a different tab. Now, contained in the occasion listener, we will test the doc.visibilityState property, pause the video when it’s hidden, and play it when seen. (After all, we first choose the video ingredient utilizing doc.querySelector().)

const video = doc.querySelector("#video");

doc.addEventListener("visibilitychange", () => {
    if (doc.visibilityState === "seen") {
        video.play();
    } else {
        video.pause();
    }
});

Now the video stops every time the consumer leaves the web page. One other use of the Web page Visibility API is to cease fetching pointless sources when the consumer doesn’t see the web page. To see this, we’ll write a perform to consistently fetch a random quote from the quotable.io API and pause this habits when the web page is hidden. Firstly, we’ll create a brand new div tag to retailer the quote in /index.html.

<div id="app">
    <video controls id="video">
        <supply src="https://smashingmagazine.com/2022/09/javascript-api-guide/./yoshi.mp4" />
    </video>
    <div id="quote"></div>
</div>

Again in /primary.js, we’ll use the Fetch API to make a name to the quotable.io endpoint https://api.quotable.io/random after which insert it into the quote div.

const quote = doc.querySelector("#quote");

const getQuote = async () => {
strive {
const response = await fetch("https://api.quotable.io/random");
const {content material, writer, dateAdded} = await response.json();
const parsedQuote = ` <q>${content material}</q> <br> <p>- ${writer}</p><br> <p>Added on ${dateAdded}</p>`;
quote.innerHTML = parsedQuote;
} catch (error) {
console.error(error);
}
};

getQuote();

Let’s shortly clarify what is occurring proper right here. We first choose the quote ingredient from the DOM. We then declare the getQuote perform, which is an async perform that enables us to make use of the await key phrase to attend till we fetch the information from the API. The information fetched is in JSON format, so we use the await key phrase another time to attend till the information is parsed right into a JavaScript object. The quotable.io API provides us—amongst different issues—the content material, writer, and dateAdded properties that we are going to inject and show into the quote div. This works, however the quote is simply fetched as soon as, so we will use setInterval() to name the perform each 10 seconds.

const quote = doc.querySelector("#quote");

const getQuote = async () => {
strive {
const response = await fetch("https://api.quotable.io/random");
const {content material, writer, dateAdded} = await response.json();
const parsedQuote = ` <q>${content material}</q> <br> <p>- ${writer}</p><br> <p>Added on ${dateAdded}</p>`;
quote.innerHTML = parsedQuote;
} catch (error) {
console.error(error);
}
};

getQuote();

setInterval(getQuote, 10000);

If the consumer minimizes the window or switches the tab, the web page would nonetheless fetch the quotes, creating an pointless community load. To unravel this, we will test if the web page is seen earlier than fetching a quote.

const getQuote = async () => {
    if (doc.visibilityState === "seen") {
        strive {
            const response = await fetch("https://api.quotable.io/random");
            const {content material, writer, dateAdded} = await response.json();
            const parsedQuote = `
            <q>${content material}</q> <br> 
            <p>- ${writer}</p><br> 
            <p>Added on ${dateAdded}</p>`;
            quote.innerHTML = parsedQuote;
        } catch (error) {
            console.error(error);
        }
    }
};

getQuote();

setInterval(getQuote, 10000);

Now, we’ll solely fetch the quote if the web page is seen to the consumer.

Assist

Broadly supported

Extra after soar! Proceed studying under ↓

Net Share API

What Is It?

The Net Share API can be among the many least-known APIs however is extraordinarily helpful. It helps you to entry the operative system’s native sharing mechanism, which is particularly helpful to cellular customers. With this API, you may share textual content, hyperlinks, and information with out the necessity to create your individual sharing mechanisms or use third-party ones.

Use Instances

They’re fairly self-explanatory. You need to use it to share content material out of your web page to social media or copy it to the consumer’s clipboard.

How To Use It?

The Net Share API provides us two interfaces to entry the consumer’s sharing system:

  1. navigator.canShare()
    Accepts the information you wish to share as an argument and returns a boolean argument relying on whether or not it’s shareable.
  2. navigator.share()
    Returns a promise that can resolve if the sharing is profitable. It invokes the native sharing mechanism and accepts the information you wish to share as an argument. Notice that it might probably solely be referred to as if a consumer has pressed a hyperlink or button, i.e., it requires transient activation. The share knowledge is an object that may have the next properties:

    • url: URL to be shared,
    • textual content: textual content to be shared,
    • title: title to be shared,
    • information: array of File objects representing information to be shared.

To see how you can use this API, we’ll recycle our prior instance and make an choice to share our quotes utilizing the Net Sharing API. To begin, we first should make a share button in /index.html:

<div id="app">
    <video controls id="video">
        <supply src="https://smashingmagazine.com/2022/09/javascript-api-guide/./yoshi.mp4" />
    </video>
    <div id="quote"></div>
    <button sort="button" id="share-button">Share Quote</button>
</div>

We direct to /primary.js and choose the share button from the DOM. Then, we create an async perform to share the information we wish.

const shareButton = doc.querySelector("#share-button");

const shareQuote = async (shareData) => {
    strive {
        await navigator.share(shareData);
    } catch (error) {
        console.error(error);
    }
};

Now, we will add a click on occasion listener to the shareButton ingredient to callback the shareQuote perform. Our shareData.textual content worth would be the quote.textContent property and the shareData.url would be the web page URL i.e the location.href property.

const shareButton = doc.querySelector("#share-button");

const shareQuote = async (shareData) => {
    strive {
        await navigator.share(shareData);
    } catch (error) {
        console.error(error);
    }
};

shareButton.addEventListener("click on", () => {
    let shareData = {
        title: "A Stunning Quote",
        textual content: quote.textContent,
        url: location.href,
    };

    shareQuote(shareData);
});

Now you may share your quotes with anybody by way of your native operative system. Nonetheless, you will need to observe that the Net Share API will solely work if the context is safe, i.e., if the web page is served over https:// or wss:// URLs.

Assist

Poorly supported

Broadcast Channel API

What Is It?

One other API I wish to speak about is the Broadcast Channel API. It permits shopping contexts to ship and obtain fundamental knowledge from one another. Looking contexts are components like a tab, window, iframe, or wherever a web page may be displayed. Because of safety causes, communication between shopping contexts isn’t allowed except they’re of the identical origin and use the Broadcast Channel API. For 2 shopping contexts to be of the identical origin, they have to share of their URL the identical protocol (e.g. http/https), area (e.g. instance.com), and port (e.g. :8080).

Use Instances

The Broadcast Channel API is mostly used to maintain a web page’s state synced throughout totally different tabs and home windows to boost consumer expertise or for safety causes. It can be used to know when a service is completed in one other tab or window. Some examples are:

  • Log a consumer in or out throughout all tabs.
  • Detect when an asset is uploaded and present it throughout all pages.
  • Instruct a service employee to do some background work.

How To Use It?

The Broadcast Channel API entails a BroadcastChannel object that can be utilized to ship messages to different contexts. Its constructor has just one argument: a string that can work as an identifier to hook up with the channel from different contexts.

const broadcast = new BroadcastChannel("new_channel");

As soon as we have now created a BroadcastChannel object with the identical identifier throughout two contexts, the brand new BroadcastChannel object could have two accessible strategies to begin speaking:

  • BroadcastChannel.postMessage() to ship a message throughout all linked contexts. It takes any type of object as its solely argument so as to ship all kinds of information.
broadcast.postMessage("Instance message");
  • BroadcastChannel.shut() to shut the channel and point out to the browser that it gained’t obtain any extra messages so it might probably acquire them into the rubbish.

To obtain a message, the BroadcastChannel has a message occasion that we will hearken to utilizing an addEventListener or its onmessage property. The message occasion has a knowledge property with the information despatched and different properties to establish the context that despatched the message, comparable to origin, lastEventId, supply, and ports.

broadcast.onmessage = ({knowledge, origin}) => {
    console.log(`${origin} says ${knowledge}`);
};

Let’s see how you can use the Broadcast Channel API by utilizing our prior instance. Our purpose can be to make one other shopping context with the identical origin and show the identical quote in each contexts. To do that, we’ll create a brand new folder named new-origin with a brand new /index.html and /primary.js information inside.

The /new-origin/index.html will probably be a brand new HTML boilerplate with a #quote div inside:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <hyperlink rel="icon" sort="picture/svg+xml" href="https://smashingmagazine.com/2022/09/javascript-api-guide/favicon.svg" />
        <meta identify="viewport" content material="width=device-width, initial-scale=1.0" />
        <title>Vite App</title>
    </head>
    <physique>
        <div id="quote"></div>
        <script sort="module" src="./primary.js"></script>
    </physique>
</html>

Within the /new-origin/primary.js file, we’ll create a brand new broadcast channel and choose the #quote ingredient from the DOM:

const broadcast = new BroadcastChannel("quote_channel");
const quote = doc.querySelector("#quote");

And in our prior /primary.js file, we’ll create a brand new BroadcastChannel object and join it to the "quote_channel". We may also modify the getQuote perform to ship the quote as a message to different contexts.

const broadcast = new BroadcastChannel("quote_channel");

//...

const getQuote = async () => {
strive {
const response = await fetch("https://api.quotable.io/random");
const {content material, writer, dateAdded} = await response.json();
const parsedQuote = ` <q>${content material}</q> <br> <p>- ${writer}</p><br> <p>Added on ${dateAdded}</p>`;
quote.innerHTML = parsedQuote;
broadcast.postMessage(parsedQuote);
} catch (error) {
console.error(error);
}
};

Again within the /new-origin/primary.js file, we’ll hearken to the message occasion and alter the quote.innerHTML every time a brand new quote is shipped.

const broadcast = new BroadcastChannel("quote_channel");
const quote = doc.querySelector("#quote");

broadcast.onmessage = ({knowledge}) => {
    quote.innerHTML = knowledge;
};

Now you may see how the quote in http://localhost:3000/new-origin/ adjustments to the quote in http://localhost:3000. You may also discover how the quote doesn’t change when the http://localhost:3000 tab is hidden because it solely fetches a quote when its web page visibility standing is seen.

Assist

Broadly supported

Internationalization API

What It Ss?

When growing an internet web page or app, it’s extraordinarily frequent to wish to translate its content material throughout different languages to succeed in a wider viewers. Nonetheless, simply translating your web page’s textual content to whichever language you want isn’t sufficient to make your content material accessible to audio system of that language since issues like dates, numbers, models, and so forth are totally different throughout international locations and should trigger confusion to your customers.

Let’s say you wish to show the date “November 8, 2022” in your webpage like “11/8/22”. This knowledge may be learn in three distinct methods relying on the reader’s nation:

  • “November 8, 2022” or MM/DD/YY by folks from the US.
  • “August 11, 2022” or DD/MM/YY by folks from Europe and Latam.
  • “August 22, 2011” or YY/MM/DD by folks from Japan, China, and Canada.

That is the place the Internationalization API (Or I18n API) comes to resolve formatting points throughout totally different languages and areas. The I18n API is an incredible device that has a number of makes use of, however we gained’t delve into them to not overcomplicate this text.

How To Use It?

The I18n API makes use of locale identifiers to work. A locale identifier is a string that expresses the consumer’s language, nation, area, dialect, and different preferences. To be exact, a locale identifier is a string that consists of subtags separated by hyphens. Subtags symbolize consumer preferences like language, nation, area, or script and are formatted within the following manner:

  1. “zh”: Chinese language (language);
  2. “zh-Hant”: Chinese language (language) written in conventional characters (script);
  3. “zh-Hant-TW”: Chinese language (language) written in conventional characters (script) as utilized in Taiwan (area).

There are extra subtags to deal with extra customers’ preferences (if you wish to be taught extra, you may test the RFC definition of language tags), however to maintain it quick, the I18n API makes use of these locale identifiers to know how you can format all of the language-sensitive knowledge.

To be extra exact, the I18n API offers an Intl object that brings a bunch of specialised constructors to work with language-sensitive knowledge. For my part, among the most helpful Intl constructors for internationalization are:

  • Intl.DateTimeFormat()
    Used to format dates and occasions.
  • Intl.DisplayNames()
    Used to format language, area, and script show names.
  • Intl.Locale()
    Used to assemble and manipulate locale identifier tags.
  • Intl.NumberFormat()
    Used to format numbers.
  • Intl.RelativeTimeFormat()
    Used to format relative time descriptions.

For our instance, we’ll concentrate on the Intl.DateTimeFormat() constructor to format the quote’s dateAdded property relying on the consumer locale. The Intl.DateTimeFormat() constructor takes two arguments: the locale string that defines the date formatting conference and the choices objects to customise how you can format the dates.

The Intl.DateTimeFormat() created object has a format() technique that takes two arguments: the Date object we wish to format and the choices object to customise how you can show the formatted date.

const logDate = (locale) => {
    const newDate = new Date("2022-10-24"); // YY/MM/DD
    const dateTime = new Intl.DateTimeFormat(locale, {timeZone: "UTC"});
    const formatedDate = dateTime.format(newDate);
    console.log(formatedDate);
};

logDate("en-US"); // 10/24/2022
logDate("de-DE"); // 24.10.2022
logDate("zh-TW"); // 2022/10/24

Notice: On the Intl.DateTimeFormat constructor’s choices argument, we set the timeZone property to "UTC" so the date isn’t formatted to the consumer’s native time. In my case, the date is parsed to “10/23/2022” with out the timeZone choice.

As you may see, the dateTime.format() adjustments the date relying on the locale’s date formatting conference. We will implement this habits on the quotes’ date utilizing the navigator.language international property, which holds the consumer’s most popular locale. To do that, we’ll create a brand new perform that takes a date string (in YYYY-MM-DD format) and returns the date formatted relying on the consumer’s locale.

const formatDate = (dateString) => {
    const date = new Date(dateString);
    const locale = navigator.language;
    const dateTimeFormat = new Intl.DateTimeFormat(locale, {timeZone: "UTC"});

    return dateTimeFormat.format(date);

};

We will add this perform contained in the getQuote() perform to parse the dateAdded date.

const getQuote = async () => {
    if (doc.visibilityState === "seen") {
        strive {
            const response = await fetch("https://api.quotable.io/random");
            const {content material, writer, dateAdded} = await response.json();
            const parsedQuote = `
            <q>${content material}</q> <br> 
            <p>- ${writer}</p><br> 
            <p>Added on ${formatDate(dateAdded)}</p>`;
            quote.innerHTML = parsedQuote;
            broadcast.postMessage(parsedQuote);
        } catch (error) {
            console.error(error);
        }
    }
};

With this, our quotes are localized to the consumer’s most popular language! In my case, my navigator.language worth is "en", so my dates are formatted to MM/DD/YY.

Assist

Broadly supported

Conclusion

After studying this text, now you can flex about figuring out the existence of those APIs and how you can use them. Regardless that they had been ranked final in consciousness within the State of JS Survey, they’re extraordinarily helpful, and figuring out how you can use them will certainly improve your growing expertise. The truth that these highly effective APIs aren’t very identified implies that there are nonetheless helpful APIs you and I nonetheless don’t find out about, so it’s the right time to discover and discover that API that can simplify your code and prevent a ton of time growing.

I hope you appreciated this text and till the following time!

Smashing Editorial(vf, yk, il)
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments