Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I detect when a user gets to a page using the back button?

Edit: What I really need to know is if there is any javascript event that will reliably fire when the user arrives at the page via the back button. I tried the onload event for the body element, but it doesn't fire on Firefox or Safari.


I'm working with some old code that tries to prevent double-submission of form data by disabling all form submission buttons as soon as the user clicks one (by listening to the form's onSubmit event). This code is applied to every form in the app, regardless of whether double-submission would even be a problem.

The problem is that if the user hits the back button in Firefox or Safari, all the submit buttons are still disabled when he gets to the page. On Firefox, they are even disabled after a refresh (only a Ctrl+F5 refresh will do it)!

I've tried listening to body's onLoad event, but FF and Safari don't fire that when you get to the page via back button. (Interestingly, it is fired on a soft refresh on FF, even though the button stays disabled.)


Here's a very simple HTML doc that will show what I mean:

<html><body>
<form name="theForm" id="theForm" action="test2.html"
      onSubmit="document.theForm.theButton.disabled = true;">
  <input id="theButton" type="submit" name="theButton" value="Click me!" />
</form>
</body></html>

Note: I've tested on WinXP with IE8, FF3.5, Safari 4, Opera 9, and Chrome 2.0. Only Safari and FF leave the button disabled when you use back to get to them.

like image 807
Kip Avatar asked Jul 15 '09 21:07

Kip


3 Answers

Isn't that the behaviour you want, so they don't double-submit using the back button?

Anyway, you could set a cookie on the following page, and detect that on load on the page with the form.

like image 75
Kev Avatar answered Oct 15 '22 15:10

Kev


Yes. In javascript you can use visited.value

function checkrefresh()
 var visited = getCookie("visited");  
{
        if((form.visited.value == '' || form.visited.value == null) && (visited != '1') ) 
        {
            document.form.visited.value = "1";
                    document.cookie = "visited=1";
                    //here you set it to something so that next time they go to the page it will no longer be nothing and you can 'disable the button' see below.

        }
        else
        {
            document.form.submitbutton.disabled=true;
        }
    } 

function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}

you would call this in the onload tag FYI.

like image 34
Eric Avatar answered Oct 15 '22 13:10

Eric


I don't think you can test for the back button specifically, but I believe you can check the browser's history position with Javascript.

like image 25
tkotitan Avatar answered Oct 15 '22 14:10

tkotitan