Javascript 关闭选项卡/浏览器时触发 Angularjs 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29150045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:55:14  来源:igfitidea点击:

Fire Angularjs event when tab/browser is closed

javascriptangularjsangularjs-scopedom-eventsangular-ui

提问by Laziale

I would like to fire JS code in Angularjs controller.

我想在 Angularjs 控制器中触发 JS 代码。

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?

当标签/浏览器结束时,我是否需要使用其他代码来消除JS代码?

采纳答案by Mark

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.

$销毁();

从父作用域中移除当前作用域(及其所有子作用域)。移除意味着对 $digest() 的调用将不再传播到当前作用域及其子作用域。删除还意味着当前范围有资格进行垃圾收集。

$destroy() 通常被诸如 ngRepeat 之类的指令用于管理循环的展开。

就在一个作用域被销毁之前,一个 $destroy 事件在这个作用域上广播。应用程序代码可以注册一个 $destroy 事件处理程序,这将使它有机会执行任何必要的清理。

请注意,在 AngularJS 中,还有一个 $destroy jQuery 事件,可用于在从 DOM 中删除元素之前清理 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:

您将不得不使用较低级别的方法 onunload 和 onbeforeunload 事件来处理这种情况,这是您可能会发现有用的另一篇文章:

javascript detect browser close tab/close browser

javascript检测浏览器关闭标签/关闭浏览器