Call a function when "Back" is clicked!

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Tea Maker
    New Member
    • Jul 2007
    • 45

    #1

    Call a function when "Back" is clicked!

    Hi, I was wondering if there's a way to call a function when a user presses on the "back" or "forward" buttons of the browsers.

    What I want is, redirect the user to a new website (let's say thescripts.com) , when he tries to click "back" , "forward', "Go", etc.... on my page.

    Is that possible? And if yes, can you please tell me how to handle these actions, plus what actions are possible (for example I know that it's impossible to do this action when someone tries to close the browser), what about "Stop" , "Refresh", etc....

    Regards,
    Wassim
  • mrhoo
    Contributor
    • Jun 2006
    • 428

    #2
    javascript will allow you to capture an unload event in all modern browsers, and you cannot cancel it. Usually you use the response to update a cookie or terminate a session just before your visitor refreshes or navigates from the page.

    Some browsers support a beforeunload event, which can throw up a confirmation dialog that forces the user to select whether to go ahead and leave- or refresh, or whatever he intended to do.

    Any code you write will only be run if the user changes his mind and cancels his action and stays on the current page. This would be a real mess if you then redirect him somewhere else.

    When a visitor wants to leave, let him go.

    Comment

    • pbmods
      Recognized Expert Expert
      • Apr 2007
      • 5821

      #3
      Heya, Wassim.

      There are certain ways of using cookies to check to see if the User used the back button....

      Comment

      • acoder
        Recognized Expert MVP
        • Nov 2006
        • 16032

        #4
        Originally posted by mrhoo
        When a visitor wants to leave, let him go.
        You're right especially in a case like this. I can add to this though:

        When a visitor doesn't want to leave, don't let him go. In an app. I wrote once, the backspace key would send the user back to the previous page. I'd detect that because it was definitely an accident. I would only try to stop them from leaving the page if they had made a change.

        Comment

        Working...