How to Close a Browser Window Opened by Your Page

Browsers restrict script-initiated window closing. A page should not assume it can close the user's existing tab simply because its load event has fired. For a utility window your application opens, retain the returned window reference and close that window when the user requests it.

Run the example

Save this complete document as windows.html and open it in a browser:

HTML
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Utility window example</title>
<button id="open" type="button">Open utility window</button>
<button id="close" type="button">Close utility window</button>
<p id="status" role="status"></p>
<script>
let utility = null;
const status = document.getElementById("status");

document.getElementById("open").addEventListener("click", () => {
  utility = window.open("about:blank", "utilityDemo", "width=500,height=300");
  status.textContent = utility ? "Window opened." : "Popup was blocked.";
});

document.getElementById("close").addEventListener("click", () => {
  if (utility && !utility.closed) {
    utility.close();
    status.textContent = "Close requested.";
  } else {
    status.textContent = "No utility window is open.";
  }
});
</script>
</html>

Click Open, then Close. The separate utility window should close while the original page remains. Manually close the utility window and click Close again to exercise the already-closed branch.

Respect browser boundaries

Open the window directly from the click handler. Delaying the call behind unrelated asynchronous work can cause the browser to classify it as an unsolicited popup. Check for a null return instead of assuming the window exists.

Do not use top.close() on page load as an application exit mechanism. It targets the top-level browsing context and may be denied. Offer a normal completion message and navigation link when the application is running in a user-opened tab. Cross-origin isolation policies and browser settings can also affect retained window references. Test the real deployed flow.

References

Window: close() method - Web APIs | MDN
The Window.close() method closes the current window, or the window on which it was called.
https://developer.mozilla.org/en-US/docs/Web/API/Window/close
Window.close
Window: open() method - Web APIs | MDN
The open() method of the Window interface loads a specified resource into a new or existing browsing context (that is, a tab, a window, or an iframe) under a specified name.
https://developer.mozilla.org/en-US/docs/Web/API/Window/open
Window.open

Author: Herman Schoenfeld