ispiro
ispiro

Reputation: 27683

Prevent using back button to see information on previous page

I have a form where users enter input. I want to prevent a different person from going back using the back button, and seeing what the first person entered.

I realize this is a problem only on the same browser etc. but that might be a problem sometimes.

I tried both Server.Transfer() and Response.Redirect() but both don't prevent it. I also tried setting the textboxes' (asp:TextBox) Text to empty in the event handler for the submit button in codebehind, but it still didn't work since the transfer overrode that.

The technology it WebForms. This is a given. I'm doing everything in codebehind, and would prefer solving this from there as well, if possible.

Upvotes: 0

Views: 445

Answers (1)

Visual Vincent
Visual Vincent

Reputation: 18310

Clearing the data from the backend (codebehind) will be too late as the redirect will, as you say, happen before the change occurs.

Instead I suggest you use Javascript on the frontend, subscribe to the window.onbeforeunload event and use that to clear your page before the redirect takes place.

An example implementation can look like:

window.addEventListener("beforeunload", function() {
    var inputs = document.getElementsByTagName("input");

    //Iterate all <input> elements on the page.
    for(var i = 0; i < inputs.length; i++) {
        var input = inputs[i];

        //Ignore all elements that don't have type="text" or type="password" (we don't want to clear buttons, etc.).
        if(["text", "password"].indexOf(input.type.toLowerCase()) < 0) { continue; }

        //Clear the element's value.
        input.value = "";
    }
});

I gave it a brief test: Right before redirecting you'll notice the text boxes being cleared, and when you return by pressing the Back button the text boxes are still empty.

Upvotes: 1

Related Questions