简体   繁体   中英

Go back or redirect to url

I've been using a back button for users to navigate back to the page they came from, problem is, if the user navigates there in a new tab or direct link, as they haven't "been anywhere" before they would get redirected back to a blank page.

Is there a solution for this? I'm thinking something like navigate back if possible, and if not it'll take you to a specific url.

This is what I have so far:

<a href="#" onclick="history.go(-1);return false;">Go back</a>

How about using document.referrer ?
It's a hack and I do not recommend it since you'll not be maintaining post data (if any). If your page doesn't need to repost any data, then this should work.

<a id="mylink" href="#">Go back</a>
$('#mylink').click(function () {
    if (history.length == 0) {
        document.location = document.referrer;
    } else {
        history.go(-1);
    }
});

I must say that I agree with SchautDollar's comment - a message is a far better warning.

If you are using php you could change link to:

echo '<a href="'. $_SERVER['HTTP_REFERER'] . '">Go back</a>';

if not you can do the same with jQuery and javascript

document.location = document.referrer;

on the link click method.

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