I have two classes when navigating from one class to another created history. Now, I want to prompt the user by a confirm whether user wants to leave the page or not.Till no
I have got this in JSNI, But its also not working in browser back button..
public native void call()/*-{
$wnd.onkeypress = GetChar;
function GetChar (event)
{
var key = event.keyCode;
var bb = event.target.nodeName;
if(key==8 && bb=="BODY")
{
var x= window.confirm("Are you sureyou want to leave the page");
if (x==true)
{
window.history.back();
}
else if(x==false)
{
return false;
}
}
}
}-*/;
Have you tried with History.addValueChangeHandler
which listens for changes in the browser's history stack?
-- EDIT --
Below code is working fine for Backspace key
in Firefox
, Chrome
as well as IE9
.
Note: Please test it for other browsers also and let me know if there is any issue.
Event.addNativePreviewHandler(new Event.NativePreviewHandler() {
@Override
public void onPreviewNativeEvent(final NativePreviewEvent event) {
boolean isFirefox = checkBrowser("Firefox");
if ((isFirefox && event.getTypeInt() == Event.ONKEYPRESS)
|| (!isFirefox && event.getTypeInt() == Event.ONKEYDOWN)) {
if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_BACKSPACE) {
Element element = Element.as(event.getNativeEvent().getEventTarget());
String tagName = element.getTagName();
System.out.println(tagName);
if (!tagName.equalsIgnoreCase("INPUT")
&& !tagName.equalsIgnoreCase("TEXTAREA")) {
boolean result = Window.confirm("Are you sure?");
if (!result) {
event.cancel();
}
}
}
}
}
});
if (checkBrowser("Firefox")) {
DOM.sinkEvents(RootPanel.get().getElement(), Event.ONKEYPRESS);
} else {
DOM.sinkEvents(RootPanel.get().getElement(), Event.ONKEYDOWN);
}
....
private static boolean checkBrowser(String browserName) {
return (Window.Navigator.getUserAgent().toLowerCase().indexOf(browserName.toLowerCase()) != -1);
}
-- EDIT --
Here is the code detect browser Back button also. For more info have a look at
How to know whether refresh button or browser back button is clicked in firefox
public native void onBeforeUnload()/*-{
$wnd.onbeforeunload = function(e) {
return 'Are you sure?';
};
}-*/;
public void onModuleLoad() {
onBeforeUnload();
}
screenshots (browser back button is clicked or page is refreshed)
Please have a look at below posts: