且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

拦截JavaScript卸载事件

更新时间:2023-12-04 14:41:10

如果你需要防止页面卸载看这个帖子:
我如何在JS中停止卸载页面(导航)



如果您需要跟踪页面卸载,可以使窗口的卸载事件(您的页面将不会退出,直到此请求完成)



如果您需要跟踪哪个自定义事件处理程序卸载页面,您将必须跟踪当前的事件处理程序,然后执行上述解决方案之一。


Assumed that i have web pages with an arbitrary amount of elements which have an event handler attached, let's say onclick. In the handler an unload event is triggered, for example by assigning window.location.

The task: I need to detect if an event handler will unload the page. How can i add another event handler which intercepts the unload event and stores it in a variable instead of triggering it?

Update

Here is an explenation, due to confusion. I have written a Java application that uses Selenium 2 to pull all information about user events. This is easily done, except for unloads. I have to wait for the pull before i can finally unload the page.

if you need to prevent page unload see this post: How do I stop a page from unloading (navigating away) in JS?

If you need to track page unloads, you can make a synchronous xhr request (tip set async=false) during your window's unload event (your page will not exit until this request finishes)

if you need to track which custom event handlers unload the page, you will have to track the current event handler and then do one of the above mentioned solutions.