Hello all,

I have a function in which onclick one window opens and there is logout option on the parent page.
when I log out i want the child window to close as well.

My native code is in Java and I need something in javascript.

Plz help

Dani AI

Generated

Good call from — keeping a reference to the child and asking it to close from the parent is the simplest solution. For real apps (JSP/Java logout flows, page reloads, multiple tabs, or cross‑origin pages) a few more robust options are worth adding so the child reliably shuts when the session ends.

Use localStorage as a logout broadcast (same origin, works across tabs/windows). In the logout flow (client-side handler or rendered by your JSP response) set a flag; every child window listens for that storage event and then cleans up and closes itself:

// set on logout (parent / logout response)
localStorage.setItem('myApp:logout', String(Date.now()));
setTimeout(() => localStorage.removeItem('myApp:logout'), 3000);
// put in the child page
window.addEventListener('storage', e => {
  if (e.key === 'myApp:logout') {
    // do any UI/cleanup then close
    window.close();
  }
});

If the child lives on a different origin, use postMessage to tell it to terminate (postMessage works cross‑origin; remember to set the correct targetOrigin). Example: parent posts a short {type: 'logout'} message and the child listens for that message and closes.

Notes and pitfalls: browsers typically allow scripts to close windows they opened; closing other windows may be blocked. If the parent reloads you lose any in‑memory handle — that’s why localStorage/postMessage is safer. Popup blockers and user settings can interfere, so provide a graceful fallback (redirect the child to a “session expired” page that asks the user to close it). For a JSP logout, emit the small client script above in the logout response to broadcast the logout to children.

Recommended Answers

All 3 Replies

Something like this, if you are closing from the parent window.

var childWindow = window.open(....);
childWindow.close();

if you want to close from the child window, you can do this:

self.close();

Hope it helps.

thank u...it helped :)

I'm glad to know it.

Just mark as solved then.

Seeya.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.