Skip to content

Browser back/Forward button with saved warning message  #609

Open
@AditiG12

Description

@AditiG12

Hi Team,

I am working on my application and I am stuck onto a solution, where I want to give a warning message on the click of back button of the browser. Whenever there are unsaved changes on the page, and user is navigating away from that page, I want to warn user that there are unsaved changes. So for this I am using below code:

window.addEventListener('popstate', function (event) {
// The popstate event is fired each time when the current history entry changes.
if(dirty==true){
var r = confirm("You pressed a Back button! Are you sure?!");

    if (r == true) {
        // Call Back button programmatically as per user confirmation.
        history.back();
        // Uncomment below line to redirect to the previous page instead.
        // window.location = document.referrer // Note: IE11 is not supporting this.
    } else {

event.preventDefault()
// Stay on the current page.
history.pushState(null, null, window.location.pathname);
}

    history.pushState(null, null, window.location.pathname);

}
}, false);

But niether preventDefault() is working nor window.beforeunload nor popstate confirm cancel is giving the desired outcome to come.

However, I created one POC where page.js is not used, and there on click of browser back button on before unload event is giving me warning pop up.

Could you please suggest solution for this as in the documentation no such case is catered

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions