DEV Community

Cover image for How to check if an opened browser window is closed or not in JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to check if an opened browser window is closed or not in JavaScript?

Originally posted here!

To check if an opened browser window is closed, you can use the closed property in referenced window object in JavaScript.

// Check if the opened browser
// window is closed or not

window.closed; // false
Enter fullscreen mode Exit fullscreen mode
  • The property returns a boolean true if the window is closed and false if the window is in the opened state.

For example to open a new browser window with google.com as the starting page, you can use window.open() method like this,

// Open a new browser window
const openedWindow = window.open(
  "https://google.com",
  "Google Search",
  "width=800,height=600,resizable,scrollbars"
);
Enter fullscreen mode Exit fullscreen mode

Note: To know more about using the using window.open() method check out the blog on How to open and close a new browser window using JavaScript?.

The openedWindow contains the reference to newly opened window properties and methods.

Now you can check if the newly opened window is closed or is currently in the opened state using the closed property in the openedWindow object.

It can be done like this,

// Open a new browser window
const openedWindow = window.open(
  "https://google.com",
  "Google Search",
  "width=800,height=600,resizable,scrollbars"
);

// check if the window is in opened or closed state
console.log(openedWindow.closed); // false
Enter fullscreen mode Exit fullscreen mode

That's it! 😃

Feel free to share if you found this useful 😃.


Top comments (1)

Collapse
 
chiragtthirdrock profile image
Chirag Thaker

Hello DEVs,
sometimes closed comes true indeed that tab is open, we just change a focus to another tab.
Anyone have idea why this is happening