AMAL BENNY
AMAL BENNY

Reputation: 51

How to know a window closed using javascript from another window/tab?

I have a window example.com/welcome.php. Using window.open(abcd.php,"mywindow","...") I open abcd.php in new window.

By using window.close() from abcd.php. I close abcd.php. How can I trigger some action in welcome.php when abcd.php closed,

Upvotes: 1

Views: 123

Answers (1)

UnnamedXAer
UnnamedXAer

Reputation: 342

You can use onunload event attached to the opened window;

var w = open('stackoverflow.com');
w.onunload = (ev) => {
    console.log('unload', ev);
};
//w.close();

Update

Set unload even inside load event to prevent from unnecessary firing unload on window open, witch happen to me in chrome at least.

var w = open('https://stackoverflow.com/users/8424614/unnamedxaer');
w.onload = () => {
    w.onunload = (ev) => {
        console.log('unload', ev);
    };
};

Update 2

The urls have to be in the same domain to work, otherwise you will get an error when trying to attach event to opened window (w) (set debugger in the line with onunload), they also must be served from same kind of server - not accessed like files when the url in browser looks like this c:/my-site/welcome.php.

Here is working example. Open CodeSandbox's console located at the bottom of the window below the browser section to see output.

Upvotes: 1

Related Questions