Open In App

How to Find Out if a Page is Opened in a New Window or New Tab in JavaScript?

Last Updated : 22 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To detect whether a page is opened in a new window or a new tab, JavaScript can be used to check the window's properties, such as its dimensions and opener status. These indicators provide insights into how the page was launched.

1. Checking the window.opener Property

This method uses the window.opener property to determine if the current page was opened by another page.

  • "window.opener" Refers to the window that opened the current page.
  • If window.opener is null, the page was opened directly (e.g., typed URL, bookmark) or refreshed.
  • If window.opener is not null, the page was opened via a link in another page.
JavaScript
if (window.opener) {
  console.log('The page is opened in a new window or tab via a link.');
} else {
  console.log('The page is opened directly or refreshed.');
}

2. Comparing Window Dimensions

This method compares the window's dimensions with the screen size to infer if the page is opened in a new tab or a resized new window.

  • window.innerWidth and window.innerHeight: Provide the dimensions of the viewport.
  • screen.width and screen.height: Provide the dimensions of the screen.
  • If the viewport matches the screen dimensions, the page is likely opened in a tab. Otherwise, it's opened in a new or resized window.
JavaScript
if (window.innerWidth === screen.width && window.innerHeight === screen.height) {
  console.log('The page is opened in a new tab.');
} else {
  console.log('The page is opened in a new window or a resized window.');
}

3. Using the Referrer Property

Check the document.referrer to determine if the page was navigated from another page.

  • document.referrer: Contains the URL of the page that linked to the current page.
  • If the referrer is empty, the page was opened directly (e.g., bookmark or typed URL).
JavaScript
if (document.referrer) {
  console.log('The page was navigated from another page.');
} else {
  console.log('The page was opened directly.');
}

Next Article
Article Tags :

Similar Reads