JavaScript History and Navigator Objects


The history and navigator objects are built into the browser’s window object and give JavaScript access to the browser's history stack and user's browser information.



1. The navigator Object – Get Browser & Device Info

The navigator object contains information about the web browser and the device running the script.

Common Properties:

console.log(navigator.userAgent);    // Full browser info
console.log(navigator.language);     // Preferred language (e.g., "en-US")
console.log(navigator.onLine);       // Is the browser online? true/false
console.log(navigator.platform);     // OS platform (e.g., Win32)
console.log(navigator.cookieEnabled); // Are cookies enabled?


Example:

if (navigator.onLine) {
  console.log("You are online");
} else {
  console.log("You are offline");
}


Other Useful Methods:

  • navigator.geolocation – Access the Geolocation API
  • navigator.clipboard – Read/write from clipboard
  • navigator.mediaDevices – Access webcam or mic


2. The history Object – Control Browser Navigation

The history object allows you to navigate through the user’s browser history (like Back and Forward buttons).



Common Methods:

Method Description
history.back() Go one step back in history (←)
history.forward() Go one step forward in history (→)
history.go(n) Go to a specific position (e.g., -1, 2)
history.length Total number of entries in the history


Example: Go Back in History

<button onclick="history.back()">Go Back</button>


Example: Jump to Specific Page in History

history.go(-2);  // Go back 2 pages


Real-World Use Cases


Navigator:

  • Detect online/offline status
  • Show browser-specific instructions
  • Handle feature availability (e.g., geolocation, clipboard)

History:

  • Custom back/forward buttons
  • SPA (Single Page App) routing
  • Improve user experience in web apps