Is there a way to call a method upon leaving a page with JSF or PrimeFaces?
14,596
Solution 1
Not when using native JSF or PrimeFaces. Your best bet would be to hook on session expiration instead.
import javax.inject.Named;
import javax.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 javax.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
event with a fallback to synchronous XHR (which is deprecated in modern browsers supporting navigator.sendBeacon()
).
See also:
Solution 2
Your problem Solution :- it work with java script
<head>
<title>onunload test</title>
<script type="text/javascript">
window.onunload = unloadPage;
function unloadPage()
{
alert("unload event detected!");
}
</script>
</head>
Also Some link for more details:- Link
Author by
Landister
Updated on July 19, 2022Comments
-
Landister almost 2 years
Is there a way to call a method upon leaving a page with JSF?
-
BalusC about 12 yearsHave you ever tried it yourself? It won't work. At least, not in normal webbrowsers.
-
prageeth about 12 yearsI dont know what are the "normal webbrowsers". But I have tried this before I put it here. Now again I tried it in Chrome, FF and IE. Have YOU tried this before commenting?
-
BalusC about 12 yearsThen you had the luck to be inside a race condition everytime where ajax request has won from the browser close event. This is however not guaranteed to be successful everytime. For sure not in production where the server usually runs at a physically different machine and the network latency is thus higher.
-
BalusC about 12 yearsThe OP want to call a JSF backing bean method, not to show a simple alert.
-
damian over 11 yearsmaybe you can programmatically click a hidden commandButton in the unload event to call a method in backing bean
-
Web Devie over 10 years@BalusC I don't see OP has written he want to call baking bean method, he want simply to call method, or can't write...