JavaScript window.closed Property: Understanding Window Closure
The window.closed property in JavaScript is a read-only property that returns a boolean value indicating whether a window has been closed or not. This property is particularly useful when dealing with pop-up windows or windows opened programmatically, allowing you to check if the window is still available before attempting to interact with it.
Purpose and Use Cases
The primary purpose of the window.closed property is to provide a means to:
- Verify if a window is still open before sending commands or accessing its properties.
- Prevent errors that might occur when trying to manipulate a closed window.
- Manage resources and clean up references to closed windows.
- Implement logic that depends on the state of other windows.
Syntax
The syntax for accessing the window.closed property is straightforward:
let isClosed = window.closed;
window: The window object you want to check. If you are running the javascript within the target window, you can omit this.closed: The read-only property that returnstrueif the window is closed, andfalseotherwise.
Property Values
The window.closed property returns one of the following values:
| Value | Description |
|---|---|
| `true` | The window has been closed. |
| `false` | The window is still open. |
Examples
Let’s explore several examples demonstrating how to use the window.closed property effectively.
Basic Check
This example demonstrates a basic check to see if a window is closed.
<!DOCTYPE html>
<html>
<head>
<title>Window Closed Check</title>
</head>
<body>
<button id="openWindowBtn">Open Window</button>
<button id="checkWindowBtn">Check Window Status</button>
<p id="windowStatus"></p>
<script>
let myWindow_basic;
const openWindowBtn_basic = document.getElementById('openWindowBtn');
const checkWindowBtn_basic = document.getElementById('checkWindowBtn');
const windowStatus_basic = document.getElementById('windowStatus');
openWindowBtn_basic.addEventListener('click', () => {
myWindow_basic = window.open('', '_blank', 'width=200,height=100');
});
checkWindowBtn_basic.addEventListener('click', () => {
if (myWindow_basic && !myWindow_basic.closed) {
windowStatus_basic.textContent = 'Window is open.';
} else {
windowStatus_basic.textContent = 'Window is closed.';
}
});
</script>
</body>
</html>
In this example:
- Clicking “Open Window” opens a new blank window.
- Clicking “Check Window Status” displays whether the window is open or closed based on the
window.closedproperty.
Preventing Errors
This example prevents errors by checking if the window is closed before trying to access its properties.
<!DOCTYPE html>
<html>
<head>
<title>Preventing Errors</title>
</head>
<body>
<button id="openWindowBtn_err">Open Window</button>
<button id="accessWindowBtn_err">Access Window</button>
<p id="result_err"></p>
<script>
let myWindow_err;
const openWindowBtn_err = document.getElementById('openWindowBtn_err');
const accessWindowBtn_err = document.getElementById('accessWindowBtn_err');
const result_err = document.getElementById('result_err');
openWindowBtn_err.addEventListener('click', () => {
myWindow_err = window.open('', '_blank', 'width=200,height=100');
});
accessWindowBtn_err.addEventListener('click', () => {
if (myWindow_err && !myWindow_err.closed) {
try {
myWindow_err.document.body.innerHTML = '<p>Accessed successfully!</p>';
result_err.textContent = 'Window accessed successfully.';
} catch (e) {
result_err.textContent = 'Error accessing window: ' + e.message;
}
} else {
result_err.textContent = 'Window is closed. Cannot access.';
}
});
</script>
</body>
</html>
In this example:
- Clicking “Open Window” opens a new blank window.
- Clicking “Access Window” attempts to modify the window’s content, but only if the window is open. If the window is closed, it displays a message indicating that it cannot be accessed.
Event Listener
This example uses an event listener to detect when a window is closed.
<!DOCTYPE html>
<html>
<head>
<title>Window Close Listener</title>
</head>
<body>
<button id="openWindowBtn_listener">Open Window</button>
<p id="windowStatus_listener"></p>
<script>
let myWindow_listener;
const openWindowBtn_listener = document.getElementById('openWindowBtn_listener');
const windowStatus_listener = document.getElementById('windowStatus_listener');
openWindowBtn_listener.addEventListener('click', () => {
myWindow_listener = window.open('', '_blank', 'width=200,height=100');
const intervalId = setInterval(() => {
if (!myWindow_listener || myWindow_listener.closed) {
windowStatus_listener.textContent = 'Window has been closed.';
clearInterval(intervalId);
} else {
windowStatus_listener.textContent = 'Window is open.';
}
}, 500);
});
</script>
</body>
</html>
In this example:
- Clicking “Open Window” opens a new blank window.
- An interval checks every 500ms if the window is closed. When it detects that the window is closed, it updates the status message and clears the interval.
Managing Resources
This example demonstrates how to manage resources and clean up references to closed windows.
<!DOCTYPE html>
<html>
<head>
<title>Managing Resources</title>
</head>
<body>
<button id="openWindowBtn_resource">Open Window</button>
<button id="checkResourceBtn_resource">Check Resource</button>
<p id="resourceStatus_resource"></p>
<script>
let myWindow_resource;
let resource_resource = { data: 'Some data' };
const openWindowBtn_resource = document.getElementById('openWindowBtn_resource');
const checkResourceBtn_resource = document.getElementById('checkResourceBtn_resource');
const resourceStatus_resource = document.getElementById('resourceStatus_resource');
openWindowBtn_resource.addEventListener('click', () => {
myWindow_resource = window.open('', '_blank', 'width=200,height=100');
});
checkResourceBtn_resource.addEventListener('click', () => {
if (myWindow_resource && !myWindow_resource.closed) {
resourceStatus_resource.textContent = 'Resource is in use.';
} else {
resource_resource = null; // Clean up resource
resourceStatus_resource.textContent = 'Window is closed. Resource released.';
}
});
</script>
</body>
</html>
In this example:
- Clicking “Open Window” opens a new blank window.
- Clicking “Check Resource” checks if the window is open. If the window is closed, it releases the resource by setting it to
null, preventing memory leaks.
Practical Application: Polling and Refreshing Data
This example demonstrates how to poll a child window for data and refresh it if closed.
<!DOCTYPE html>
<html>
<head>
<title>Polling and Refreshing Data</title>
</head>
<body>
<button id="openDataWindowBtn">Open Data Window</button>
<button id="checkDataBtn">Check Data Window</button>
<p id="dataWindowStatus"></p>
<script>
let dataWindow;
const openDataWindowBtn = document.getElementById('openDataWindowBtn');
const checkDataBtn = document.getElementById('checkDataBtn');
const dataWindowStatus = document.getElementById('dataWindowStatus');
openDataWindowBtn.addEventListener('click', () => {
// Create a function to generate some sample data
function generateData() {
return `
<!DOCTYPE html>
<html>
<head><title>Data Window</title></head>
<body>
<h1>Data Window</h1>
<p>Data updated at: ${new Date().toLocaleTimeString()}</p>
</body>
</html>
`;
}
// Open a new window
dataWindow = window.open('', '_blank', 'width=300,height=200');
// Write the initial data to the new window
if (dataWindow) {
dataWindow.document.open();
dataWindow.document.write(generateData());
dataWindow.document.close();
}
});
checkDataBtn.addEventListener('click', () => {
if (dataWindow && !dataWindow.closed) {
// If the window is open, update its content
dataWindow.document.open();
dataWindow.document.write(`
<!DOCTYPE html>
<html>
<head><title>Data Window</title></head>
<body>
<h1>Data Window</h1>
<p>Data updated at: ${new Date().toLocaleTimeString()}</p>
</body>
</html>
`);
dataWindow.document.close();
dataWindowStatus.textContent = 'Data window updated.';
} else {
dataWindowStatus.textContent = 'Data window is closed.';
}
});
</script>
</body>
</html>
In this example:
- Clicking “Open Data Window” opens a new window and populates it with some initial data.
- Clicking “Check Data Window” checks if the window is open. If it is, it updates the data; otherwise, it indicates that the window is closed.
Tips and Best Practices
- Always check
window.closedbefore interacting with a window to prevent errors. - Use event listeners or intervals to detect when a window is closed, especially for long-running applications.
- Release resources and clean up references to closed windows to avoid memory leaks.
- Consider using try-catch blocks when accessing window properties to handle potential errors gracefully.
Browser Support
The window.closed property is supported by all major browsers, including:
- Chrome
- Firefox
- Safari
- Edge
- Opera
It has been widely supported since the early versions of these browsers. 🎉
Conclusion
The window.closed property is an essential tool for managing and interacting with windows in JavaScript. By understanding its usage and incorporating it into your code, you can create more robust and error-free web applications. Whether you’re dealing with pop-up windows, managing resources, or implementing complex window interactions, the window.closed property provides a reliable way to check the state of a window and handle it appropriately. 👍








