带有if / else功能的Javascript / php后退按钮

Is it possible to have a back button feature that goes back from the previous page if it was coming from the website itself (i.e. page 1 to page 2). But when user come from other site (i.e. google search result) it links to a general page from my website.

I am new to javascript and the only way I know is the href="javascript:history.go(-1)" which does not do what I want. Can someone provide an example or link to a site that can help me? thx.

If you are talking about making your own back button, then absolutely. You would need to track the referring page in php using $_SERVER['HTTP_REFERER'], and if that page is not on your site, fudge the link so it goes to your general page.

If you want the same behaviour with the browser built in back button, I think you are out of luck, you can't access the history directly for security reasons, so you have no way of knowing if the last link is on your domain or not.

You can't change the browsers back button, but you can create a regular button on the website that does this, which is what I'm guessing you want.

Something like this, checking the referrer should work

<?php

    $referrer = $_SERVER['HTTP_REFERER'];
    if (strpos($referrer, 'example.com') !== FALSE)) {
        echo '<a href="#" onclick="history.go(-1)">Go Back</a>';
    } else {
        echo '<a href="example.com/general_page.php">Go Back</a>';
    }

?>