简体   繁体   中英

Detect if URL change was back

I have a web app that uses some subtle effects when navigating. Essentially the pages "slide" in from the right.

Everything in the app is based changes to the hash and all that is working great.

What I'm simply looking for is a way to determine if the change to the URL is a "back" action. I'm not going to try to affect the change-- my app already handles that perfectly. I just want to reverse the "effect". In other words, if I know they are clicking "back" I want to slide in from the left left instead of the usual action of sliding in from the right.

Keep in mind I don't need help with the animation itself or keeping track of app state in the hash-- I only need to know how to know if the change is a "Back" action.

Also, I really don't want to keep a list of the hash states in the app as users click around to try and determine if they are going "back". I might consider that if it's really the only option, but I hoping to find a solution that just knows if the user initiated back (Back button, history.go(-1), right click "Go Back", etc).

Is this information available in javascript without explicitly keeping track of changes to the hash?

Use a previous page variable. I'm going to assume that when you are "changing" pages you are doing it through a central function.

In your goto page function

// Try to get the previous page if known (will be 'unidentified' if unknown)
var prevPage = window.previousPage;

// Set this page as the previous before moving.
window.previousPage = 'this page';

// Assume that gotoPage is where we are headed
if(gotoPage == prevPage)
{
    // We're going back!
}
else
{
    // We're going forward!
}

PS

I am using the window.previousPage as the general container and using prevPage to compare in scope. This is on by design to limit the number of places you would have to set window.previousPage

EDIT:

Didn't think about multiple going backs, same idea using an array (not tested but this is the general idea)

var prevPage = '';

if( Object.prototype.toString.call( window.previousPage ) === '[object Array]' )
    prevPage = window.previousPage[ window.previousPage.length - 1 ];

if(prevPage == gotoPage)
{
    // Splice out the last entry
    window.previousPage.splice( window.previousPage.length - 1, 1);
    // Going back DO NOT add new window.previousPage
}
else
{
    // Going forward add the previousPage before changing
    window.previousPage[ window.previousPage.length ] = 'this page';

    // Move Page
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM