Window Object in JavaScript

Window Object in JavaScript

ยท

7 min read

in this article, we learn about window object in depth.

What is BOM?

The Browser Object Model (BOM) is a set of APIs provided by the web browser to interact with the browser window and other browser-specific features.

The BOM consists of the objects navigator, history, screen, location and document which are children of the window object

The default object of browser is window means you can call all the functions of window by specifying window or directly. For example:

window.alert("hello  ");  

same as

alert("hello ");

An object of the window is created automatically by the browser.

Window innerWidth

Get the inner width of the browser window (in pixels)

let x=window.innerWidth;
console.log(x); // 980

Window innerHeight

Get the inner height of the browser window (in pixels)

let y = window.innerHeight;
console.log(y); // 1743

Window document

Access the DOM document object

let z=window.document;
console.log(z); //  document file

Window open

Open a new window or tab with the specified URL

window.open('https://www.google.com', '_blank');

Window close

Close the current browser window or tab

window.close();

Window resizeTo

resizes the browser window to the specified width and height in pixels. It takes two parameters width and height. syntax resizeTo(width, height)

Window Screen Object

The screen object in JavaScript represents the properties and methods related to the user's screen or display. It provides information about the screen dimensions, color depth, available screen space, and other screen-related features.

Accessing Screen Dimensions:

console.log(screen.width);  // Get the width of the screen in pixels
console.log(screen.height); // Get the height of the screen in pixels
console.log(screen.availWidth);  // Get the available width of the screen in pixels (excluding taskbars)
console.log(screen.availHeight); // Get the available height of the screen in pixels (excluding taskbars)

Color Depth and Pixel Depth:

console.log(screen.colorDepth);   // Get the color depth of the screen (in bits per pixel)
console.log(screen.pixelDepth);   // Get the pixel depth of the screen (in bits per pixel)

Opening a New Window with Screen Dimensions:

// Open a new window with dimensions equal to the screen size
window.open('https://www.example.com', '_blank', `width=${screen.width},height=${screen.height}`);

Detecting the Orientation of the Screen:

console.log(screen.orientation); 
// Get the orientation of the screen (landscap

Window location Object

The location object in JavaScript represents the current URL of the web page and provides various properties and methods to work with the URL.

  1. Accessing the Current URL:
console.log(location.href);      // Get the full URL of the current page
console.log(location.protocol);  // Get the protocol of the URL (e.g., http:, https:)
console.log(location.host);      // Get the host name and port number of the URL
console.log(location.hostname);  // Get the host name of the URL
console.log(location.port);      // Get the port number of the URL
console.log(location.pathname);  // Get the path of the URL
console.log(location.search);    // Get the query string of the URL
console.log(location.hash);      // Get the fragment identifier (hash) of the URL
  1. Navigating to a Different URL:
// Redirect to a new URL
location.href = 'https://www.example.com';

// Reload the current page
location.reload();

// Navigate back to the previous page
history.back();

// Navigate forward to the next page
history.forward();
  1. Modifying the Current URL:
// Change the hash (fragment identifier) of the URL
location.hash = 'section1';

// Replace the current URL without adding it to the browser history
location.replace('https://www.example.com');

// Modify the query parameters of the URL
location.search = 'param1=value1&param2=value2';
  1. Parsing the Query Parameters:
// Get the value of a specific query parameter
const searchParams = new URLSearchParams(location.search);
console.log(searchParams.get('param1'));

// Iterate over all query parameters
searchParams.forEach((value, key) => {
  console.log(`${key}: ${value}`);
});

Window history Object

The history object in JavaScript represents the browser's session history, which includes the URLs visited by the user within the current tab or window. It provides methods to navigate back and forth in the history, as well as to manipulate the browser's session history.

  1. Navigating Back and Forward:
// Go back to the previous page
history.back();

// Go forward to the next page
history.forward();

// Go back or forward by a specific number of pages
history.go(-2);  // Go back 2 pages
history.go(3);   // Go forward 3 pages
  1. Manipulating the Session History:
// Add a new entry to the session history
history.pushState(null, null, 'page2.html');

// Replace the current entry in the session history
history.replaceState(null, null, 'page3.html');

// Remove the current entry from the session history
history.go(-1);
  1. Detecting Changes in the Session History:
// Listen for the "popstate" event, triggered when the user navigates back or forward
window.addEventListener('popstate', function(event) {
  console.log('Navigated to:', document.location.href);
});
  1. Getting the Length of the Session History:
console.log(history.length);  // Number of entries in the session history

Window Navigator Object

The navigator object in JavaScript provides information about the user's browser and operating system. It offers various properties and methods to access and retrieve information related to the browser and its capabilities.

  1. Getting Browser Information:
console.log(navigator.userAgent);      // User agent string
console.log(navigator.vendor);         // Browser vendor
console.log(navigator.platform);       // Operating system platform
console.log(navigator.language);       // User's preferred language
console.log(navigator.cookieEnabled);  // Check if cookies are enabled
  1. Detecting Browser Features:
console.log(navigator.javaEnabled());       // Check if Java is enabled
console.log(navigator.geolocation);         // Check if geolocation is supported
console.log(navigator.getBattery);          // Check if battery API is supported
console.log(navigator.mediaDevices);        // Check if media devices API is supported
console.log(navigator.serviceWorker);       // Check if service workers are supported
  1. Redirecting to Another URL:
if (navigator.userAgent.includes('MSIE')) {
  window.location.href = 'unsupported.html';
}
  1. Opening a New Browser Window/Tab:
navigator.vibrate(200);  // Vibrate the device (if supported)
navigator.clipboard.writeText('Hello');  // Copy text to clipboard (if supported)
navigator.share({ title: 'Page Title', url: 'https://example.com' });  // Share

Popup Boxes

  1. Alert Box: The alert box displays a message and an OK button. It is used to display information or notify the user about something.
alert("This is an alert message!");
  1. Confirm Box: The confirm box displays a message, along with OK and Cancel buttons. It is used to ask the user for confirmation. The function returns true if the user clicks OK and false if the user clicks Cancel.
const result = confirm("Are you sure you want to proceed?");
if (result) {
  // User clicked OK
} else {
  // User clicked Cancel
}
  1. Prompt Box: The prompt box displays a message along with an input field for the user to enter some text. It is used to prompt the user for input. The function returns the value entered by the user, or null if the user clicks Cancel.
const name = prompt("Please enter your name:");
if (name) {
  // User entered a name
} else {
  // User clicked Cancel
}

Timing Events

JavaScript can be executed in time-intervals. This is called timing events.

The two key methods to use with JavaScript are:

  • setTimeout(function, milliseconds)
    Executes a function, after waiting a specified number of milliseconds.

  • setInterval(function, milliseconds)
    Same as setTimeout(), but repeats the execution of the function continuously.

Please refer to my previous article related to timing events click here ๐Ÿ‘ˆ

let's discuss about

what is the difference between a window object and a document object?

  1. Window Object:

    • The window object is the global object in the browser environment.

    • It represents the entire browser window or tab.

    • It provides access to various properties and methods related to the browser, such as document, location, navigator, history, setTimeout, etc.

    • It acts as the entry point to interact with the browser's Document Object Model (DOM) and Browser Object Model (BOM).

    • Examples:

      • window.location.href accesses the current URL of the browser.

      • window.alert('Hello') displays an alert dialog box.

  2. Document Object:

    • The document object is a property of the window object.

    • It represents the current web page loaded in the browser window.

    • It provides access to various properties and methods to manipulate and interact with the elements of the web page.

    • It is part of the DOM (Document Object Model), which represents the structure of the web page as a tree-like structure of elements.

    • Examples:

      • document.getElementById('myElement') retrieves an HTML element with the specified ID.

      • document.createElement('div') creates a new HTML element dynamically.

In summary, the window object represents the entire browser window and provides access to various browser-related properties and methods, while the document object represents the currently loaded web page and provides access to DOM-related properties and methods for manipulating the elements on the page.

ย