JavaScript Window close() Method

Beginner
⏱️ 7 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Window control

What You’ll Learn

The close() method shuts a browser window. This tutorial covers syntax, which windows can actually be closed, pairing with open(), five examples, and browser security rules beginners must know.

01

Syntax

window.close()

02

Popups

Script-opened windows

03

Main tab

Often blocked

04

Pair

With open()

05

Check

.closed property

06

Return

undefined

Introduction

Sometimes a web app opens a helper window—a login popup, a print preview, or a small tool panel. When the job finishes, JavaScript should shut that window cleanly. The window.close() method requests exactly that.

Important caveat: browsers protect users from scripts that try to close tabs they opened themselves. close() works best on windows your code created with window.open(), especially when triggered by a user action like a button click.

Understanding the close() Method

window.close() takes no arguments and returns undefined. Called on the global window, it targets the current browsing context. Called on a reference returned from window.open(), it targets that popup instead: popupWindow.close().

After closing, the reference’s closed property becomes true. Always check before reusing a popup object—calling methods on a closed window throws errors in some browsers.

💡
Beginner Tip

If window.close() seems to do nothing on your main tutorial tab, that is normal browser behavior—not a bug in your code. Test with a popup you opened via window.open().

📝 Syntax

General form of Window.close():

JavaScript
window.close();
// close a popup reference:
popupWindow.close();

Parameters

  • None.

Return value

  • undefined.

Related APIs

  • window.open() — create a window your script may close later.
  • window.opener — inside a popup, reference the page that opened it.
  • popupWindow.closed — boolean indicating whether the popup is gone.

⚡ Quick Reference

TopicDetail
Close current contextwindow.close()
Close popuppopupRef.close()
Opens withwindow.open()
Main user tabUsually cannot close
Check if shutpopupRef.closed === true
Return valueundefined

📋 close() vs open()

Open creates a controllable window; close removes it. Store the reference open() returns.

Open
open(url, name)

Returns Window ref

Close
ref.close()

Shuts that window

Self close
window.close()

Inside the popup

Status
ref.closed

True after close

Examples Gallery

Use the Try-it links to open small popups and close them. Popups opened by your script are the reliable way to see close() in action.

📚 Getting Started

Close from a button click—works on script-opened windows, often blocked on the main tab.

Example 1 — Close Button (Current Window)

Wire a button to call window.close(). On a normal tab the browser may ignore the request.

JavaScript
document.getElementById("closeBtn").addEventListener("click", function () {
  window.close();
  console.log("close() called — may be blocked on main tabs.");
});
Try It Yourself

How It Works

The method runs, but the browser decides whether closing is allowed. User-opened tabs are protected; popups opened by script are not.

📈 Practical Patterns

Opener closes popup, popup closes itself, timed shutdown, and status checks.

Example 2 — Opener Closes a Popup

Store the return value of open(), then call close() on that reference.

JavaScript
let popupWindow = null;

document.getElementById("openBtn").onclick = function () {
  popupWindow = window.open("", "DemoPopup", "width=320,height=200");
  popupWindow.document.write("<p>Hello from the popup!</p>");
};

document.getElementById("closePopupBtn").onclick = function () {
  if (popupWindow && !popupWindow.closed) {
    popupWindow.close();
    console.log("Popup closed from opener.");
  }
};
Try It Yourself

How It Works

The opener page keeps a live reference to the child window. Calling popupWindow.close() shuts only that popup—the parent tab stays open.

Example 3 — Popup Closes Itself

Inside the child window, window.close() targets the popup browsing context.

JavaScript
<!-- Content written into a popup -->
<p>Thanks! You may close this window.</p>
<button type="button" onclick="window.close()">Close</button>
Try It Yourself

How It Works

OAuth flows, payment confirmations, and “Done” dialogs in popups often use this self-close pattern after the user finishes a task.

Example 4 — Auto-Close Popup After a Delay

Close a script-opened popup automatically with setTimeout.

JavaScript
const popup = window.open("", "AutoClose", "width=300,height=160");
popup.document.write("<p>Closing in 3 seconds…</p>");

setTimeout(function () {
  popup.close();
  console.log("Popup auto-closed.");
}, 3000);
Try It Yourself

How It Works

Because the opener created the popup, timed close() usually succeeds. Prefer a visible countdown so users are not surprised.

Example 5 — Check closed Before Reusing a Reference

Avoid calling methods on a window that is already shut.

JavaScript
let popup = window.open("", "CheckClosed", "width=280,height=140");

function showStatus() {
  if (!popup || popup.closed) {
    console.log("Popup is closed.");
    return;
  }
  console.log("Popup is still open.");
}

popup.close();
showStatus();  // "Popup is closed."
Try It Yourself

How It Works

The closed boolean updates after close(). Guard checks prevent errors when users manually close the popup with the browser’s X button.

🚀 Common Use Cases

  • OAuth / login popups — close after redirect back with a token.
  • Print preview windows — shut helper window after printing.
  • Wizard steps — child window closes when flow completes.
  • Payment confirmation — popup closes itself on success.
  • Multi-window tools — opener closes outdated popups before opening new ones.
  • Cleanup on logout — close auxiliary windows the app opened.

🧠 What Happens When You Call close()

1

Request close

Script calls close() on a Window object.

Call
2

Policy check

Browser verifies the window may be closed (script-opened vs user tab).

Security
3

Window unloads

If allowed, the window closes and closed becomes true.

Unload
4

Reference stale

Opener should stop using the popup object except to read closed.

📝 Notes

  • Pop-up blockers may prevent open(); without a popup there is nothing to close().
  • Cross-origin popups limit what the opener can read— but same-origin close() still works.
  • Do not use close() as a substitute for hiding modal UI—prefer in-page dialogs for main tabs.
  • Mobile browsers may treat popups as new tabs with different close behavior.
  • Closing a window stops its timers and scripts immediately.
  • Modern apps often use iframe modals instead of popups to avoid blocker issues.

Browser Support

Window.close() exists in all browsers, but whether closing succeeds depends on how the window was opened—not on missing API support.

Universal API · Restricted behavior

Window.close()

The method is available everywhere. Script-opened popups close reliably; user-opened main tabs are protected in Chrome, Firefox, Safari, and Edge.

100% API availability
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
close() Universal

Bottom line: Test with windows you opened via open(). Never depend on closing the user's primary tab.

Conclusion

window.close() shuts browser windows your application controls, especially popups from window.open(). It is not a general “close this tab” tool for pages the user opened manually.

Store popup references, check closed, and tie close actions to clear user intent. For main-page UI, use modals instead of abusing close().

💡 Best Practices

✅ Do

  • Close popups you opened with window.open()
  • Check popup.closed before reusing references
  • Close from user clicks when possible
  • Null out references after closing
  • Prefer in-page modals for main-window UX

❌ Don’t

  • Expect close() to shut the user’s main tab
  • Auto-close windows without warning the user
  • Leave orphan popups open after logout
  • Call methods on a closed popup reference
  • Rely on popups when blockers make them unreliable

Key Takeaways

Knowledge Unlocked

Five things to remember about close()

Your foundation for managing popup windows in JavaScript.

5
Core concepts
🔌 02

Popups

Script-opened OK.

Scope
🚫 03

Main tab

Often blocked.

Security
🔄 04

With open()

Store ref.

Pair
05

.closed

Check status.

Guard

❓ Frequently Asked Questions

It asks the browser to close the current window or tab. It works reliably on windows created with window.open(). Browsers usually block closing the main tab the user opened manually.
No. For security, scripts cannot freely close tabs the user navigated to directly. close() is meant for popups and helper windows your code opened.
Keep the returned window reference and call popup.close() from the opener page, or call window.close() inside the popup itself (often after a button click).
No. Call window.close() with no arguments. It returns undefined.
On a Window object reference, closed is true after that window has been shut. Use it to avoid calling methods on a dead popup reference.
Browsers prefer user gestures for closing windows. Auto-closing popups may work when your script opened them, but closing the user's main tab without interaction is typically blocked.
Did you know?

Before single-page apps were common, many sites used window.open() for help docs and close() when done. Today, same-page modals and routes replace most of those popups—but OAuth and payment flows still rely on the open/close pattern.

Continue to confirm()

Learn how to show an OK/Cancel dialog with the window.confirm() method.

confirm() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful