Friday, 9 August 2013

Browsers back button click with confirm box

Browsers back button click with confirm box

Need to create the javascript confirm pop up on click of browsers back
button. If I click on back button pop up will come up and say "you want to
go ahead ?" if click on Yes then it would have redirected to previous
page.
I have following code it is not working as per the requirement.
if(window.history && history.pushState){ // check for history api support
window.addEventListener('load', function(){
// create history states
history.pushState(-1, null); // back state
history.pushState(0, null); // main state
history.pushState(1, null); // forward state
history.go(-1); // start in main state
this.addEventListener('popstate', function(event, state){
// check history state and fire custom events
if(state = event.state){
event = document.createEvent('Event');
event.initEvent(state > 0 ? 'next' : 'previous', true,
true);
this.dispatchEvent(event);
var r = confirm("Would you like to save this draft?");
if(r==true) {
// Do nothing
} else {
self.location = document.referrer;
}
// reset state
history.go(-state);
}
}, false);
}, false);
}
Any help in this would be really appreciable.

No comments:

Post a Comment