What is JavaScript Navigator and Cookies

#js cookies

#js Navigator

JavaScript Navigator

The JavaScript `navigator` object provides information about the browser and the environment in which the script is running. It is part of the Windows interface and can be used to obtain information such as the user's browser, platform, and user agent string. This object is particularly useful for detecting the user's environment and customizing the behavior of your web application accordingly.

Here are some key properties and methods of the `navigator` object:

  • navigator.appName: Returns the name of the browser.
  • navigator.appVersion: Returns the version information of the browser.
  • navigator.userAgent: Returns the user-agent string for the current browser.
  • navigator.platform: Returns the platform on which the browser is running.
  • navigator.language: Returns the preferred language of the user.
  • navigator.onLine: Returns a boolean value indicating whether the browser is online.

Example usage:

console.log(navigator.appName);
console.log(navigator.appVersion);
console.log(navigator.userAgent);
console.log(navigator.platform);
console.log(navigator.language);
console.log(navigator.onLine);

JavaScript Cookies

Cookies are small pieces of data that are stored on the user's computer by the web browser while browsing a website. They are used to remember information about the user across different pages or visits. Cookies can store various types of data, such as user preferences, session information, and tracking information.

JavaScript provides an interface to create, read, and delete cookies through the `document.cookie` property.

  • Creating a Cookie:
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";

This creates a cookie named username with the value JohnDoe that expires at the end of 2024 and is accessible throughout the entire website.

  • Reading a Cookie:
let cookies = document.cookie;
console.log(cookies);

This returns a string containing all the cookies, separated by semicolons.

  • Deleting a Cookie:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";

This deletes the cookie by setting its expiration date to a time in the past.

For more in-depth tutorials and examples on JavaScript and web development, you can visit Guru Labs.