Integrated functionality thanks to the JavaScript Navigator interface

Techelopment - Oct 8 - - Dev Community

JavaScript's Navigator interface is an essential tool for getting information and interacting with the browser environment. It offers various methods for gathering data about the user's device, connection, and other features that can be useful in developing modern web applications.

In this article, we will explore the main methods of the Navigator interface, focusing on the most practical and up-to-date ones, and we will see examples of how to use them within our applications.

🔗 Do you like Techelopment? Check out the site for all the details!

Navigator Interface Main Methods

1. navigator.userAgent

The navigator.userAgent method returns a string containing information about the browser, such as its name, version, and operating system.
Example:

const userAgent = navigator.userAgent;
console.log(userAgent); //Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.199 Safari/537.36
Enter fullscreen mode Exit fullscreen mode

This method can be useful to determine which browser the user is using and adapt the application's behavior accordingly, such as showing specific messages for unsupported browsers.

2. navigator.language

navigator.language returns the language code set in the user's browser, usually in RFC 4646 format (for example "it-IT" for Italian in Italy).
Example:

const language = navigator.language;
console.log(language); //it-IT
Enter fullscreen mode Exit fullscreen mode

This method is often used to automatically adapt the application interface language, based on user preferences.

3. navigator.geolocation

Geolocation API allows you to get the geographic location of the user. It provides various methods such as getCurrentPosition(), watchPosition() and clearWatch() to get or monitor the location.
Example:

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(position => {
    const { latitude, longitude } = position.coords;
    console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
  }, error => {
    console.error('Error retrieving position', error);
  });
} else {
  console.log("Geolocation not supported.");
}
Enter fullscreen mode Exit fullscreen mode

This method can be used in maps, location-based suggestions, and other features that require geographic data.

4. navigator.onLine

The navigator.onLine method returns a boolean value indicating whether the browser is currently connected to the Internet.
Example:

if (navigator.onLine) {
  console.log("You are connected to the Internet.");
} else {
  console.log("You are offline.");
}
Enter fullscreen mode Exit fullscreen mode

This method is useful for creating applications that need to handle disconnection situations, allowing the app to activate an offline mode or notify the user when the connection is lost.

5. navigator.cookieEnabled

navigator.cookieEnabled returns a boolean value indicating whether cookies are enabled in the browser.
Example:

if (navigator.cookieEnabled) {
  console.log("Cookie enabled.");
} else {
  console.log("Cookie disabled.");
}
Enter fullscreen mode Exit fullscreen mode

This method is essential to ensure that features that depend on cookies, such as authentication, can function properly.

6. navigator.storage

navigator.storage allows you to interact with browser storage, such as localStorage and sessionStorage. It also provides ways to check for persistent storage.
Example:

navigator.storage.estimate().then(estimate => {
  console.log(`Available space: ${estimate.quota} byte`);
  console.log(`Used space: ${estimate.usage} byte`);
});
Enter fullscreen mode Exit fullscreen mode

Practical use: storage is useful for monitoring how much space the app is using in the browser and for managing long-term data storage, such as preferences or user states, via localStorage or IndexedDB.

Now on to my favorites 😊

7. navigator.credentials

The credentials API is useful for managing the login process, allowing you to get and store user credentials. It is used to make the authentication process smoother.
Example of using saved credentials:

navigator.credentials.get({
  password: true,
  federated: { providers: ['https://accounts.google.com'] }
}).then(credential => {
  if (credential) {
    console.log("Credentials recovered:", credential);
    // Use credentials to log in.
  }
});
Enter fullscreen mode Exit fullscreen mode

This API facilitates automatic login, reducing the need to manually enter credentials each time you access a site.

8. navigator.sendBeacon()

With the introduction of client-side logic based on JavaScript or frameworks like React and Angular, the possibility of having server-side logs that track what happens during the execution of the code has been lost (if you are thinking of console.log I remind you that it is only useful on the client side 😏).

sendBeacon() could be a solution as it allows you to send data to the server asynchronously and reliably even when the page is closing. It is particularly useful for sending analytics data without blocking the closing of the page. It is also much simpler than traditional techniques like XHR or fetch for small data transmissions.
Example:

const url = "/log";
const data = new Blob(["log data"], { type: 'text/plain' });
navigator.sendBeacon(url, data);
Enter fullscreen mode Exit fullscreen mode

With this method you can send tracking or log data without interfering with the user experience, as it does not block navigation or closing the page.

9. navigator.share()

The share() API allows you to open the native sharing system of the device, allowing the user to share content such as text, links or files.
Example:

if (navigator.share) {
  navigator.share({
    title: 'Techelopment',
    text: 'Take a look!',
    url: 'https://www.techelopment.it'
  }).then(() => {
    console.log("Shared successfully.");
  }).catch(err => {
    console.error('Sharing error:', err);
  });
} else {
  console.log("Sharing API not supported.");
}
Enter fullscreen mode Exit fullscreen mode

This API is particularly useful to allow users to easily share content directly from the browser, without having to copy and paste links manually.
You can see an example of use on my site www.techelopment.it by clicking on the share icon:

Techelopment sharing

Inavigator.share menu

Keep in mind

The methods described above allow you to create more interactive and optimized web applications to improve the user experience (UX).
The combined use of these APIs allows you to improve the responsiveness of your applications and offer personalized and fluid experiences, making the web even more dynamic and interactive.


Follow me #techelopment

Official site: www.techelopment.it
Medium: @techelopment
Dev.to: Techelopment
facebook: Techelopment
instagram: @techelopment
X: techelopment
telegram: @techelopment_channel
youtube: @techelopment
whatsapp: Techelopment


References

Credential Management API
Estimating Available Storage Space

. . . . . . . . . . . . .
Terabox Video Player