Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to call a method upon leaving a page with JSF or PrimeFaces?

Is there a way to call a method upon leaving a page with JSF?

like image 316
Landister Avatar asked Apr 02 '12 21:04

Landister


1 Answers

Not when using native JSF or PrimeFaces. Your best bet would be to hook on session expiration instead.

import jakarta.inject.Named;
import jakarta.enterprise.context.SessionScoped;

@Named
@SessionScoped
public class Bean implements Serializable {

    @PreDestroy
    public void destroy() {
        // Your code here.
    }
}

If you happen to use the JSF utility library OmniFaces, then you can use its @ViewScoped. This will call the @PreDestroy when leaving the page referencing the view scoped bean.

import jakarta.inject.Named;
import org.omnifaces.cdi.ViewScoped;

@Named
@ViewScoped
public class Bean implements Serializable {

    @PreDestroy
    public void destroy() {
        // Your code here.
    }
}

Under the covers, it works by triggering a navigator.sendBeacon() during the window beforeunload or pagehide event with a fallback to synchronous XHR (which is deprecated in modern browsers supporting navigator.sendBeacon()).

See also:

  • How detect and remove (during a session) unused @ViewScoped beans that can't be garbage collected
like image 7
BalusC Avatar answered Oct 21 '22 07:10

BalusC