Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire Angularjs event when tab/browser is closed

I would like to fire JS code in Angularjs controller.

I have this:

$scope.$on('$destroy', function () {
            alert('page1');
        });

This is working fine when I'm navigating away from the page which is using that controller but its not working when I'm closing tab/browser.

Do I need to use some other code to fire JS code when tab/browser is closing?

like image 369
Laziale Avatar asked Mar 19 '15 16:03

Laziale


People also ask

How do I capture close browser events?

A tab or window closing in a browser can be detected by using the beforeunload event. This can be used to alert the user in case some data is unsaved on the page, or the user has mistakenly navigated away from the current page by closing the tab or the browser.

How can I tell if my browser window is closed?

To check if an opened browser window is closed, you can use the closed property in referenced window object in JavaScript. The property returns a boolean true if the window is closed and false if the window is in the opened state.

How do you handle browser tab close angular not close refresh?

tabWasClosed = true; } return false; } doUnload() { if (this. tabWasClosed) { ... perform logout action ... } } So you can use the visibilityState with the beforeunload event to differentiate whether the user refreshed or closed the tab.


1 Answers

From the angular docs:

$destroy();

Removes the current scope (and all of its children) from the parent scope. Removal implies that calls to $digest() will no longer propagate to the current scope and its children. Removal also implies that the current scope is eligible for garbage collection.

The $destroy() is usually used by directives such as ngRepeat for managing the unrolling of the loop.

Just before a scope is destroyed, a $destroy event is broadcasted on this scope. Application code can register a $destroy event handler that will give it a chance to perform any necessary cleanup.

Note that, in AngularJS, there is also a $destroy jQuery event, which can be used to clean up DOM bindings before an element is removed from the DOM.

This just handles the situation where the scope itself is being destroyed, that does not seem to occur when the tab/browser is closed though.

You will have to use lower level methods onunload and onbeforeunload events to handle this situation, here is another post you may find useful:

javascript detect browser close tab/close browser

like image 182
Mark Avatar answered Oct 07 '22 02:10

Mark