Question

The problem:

I need to start with a URL with a query string containing a URL of a second page - http://www.firstURL.com/?http://www.secondURL.com. On the target page of the first URL, the query string is parsed to extract the second URL and the browser is re-directed to the second URL. This is done on $(document).ready so that it's automatic. This all works fine, but of course falls in a hole if the user hits the back button on the second URL. Here's the basic code:

$(document).ready(function() {
    var s = location.search;
    if(s != '') {
        var split = s.split('?');
        var loc = split[1].replace('?', '');
        location.href = '' + loc + '';
    } else {
        //do something else on the target page..
    }
});

I've tried creating a conditional case where, if the referrer is the 2nd URL (loc in the code above), the re-direction doesn't execute, but it seems that in the case of a re-direction, the back button doesn't return the referrer.

I have to do all this client side - I have no access to the server.

Is there some way to prevent the re-direction triggering on a back button click? Thanks.

Was it helpful?

Solution

Once you hit the second page, set a cookie in your browser indicating that the second page has been visited. In the first page, before doing the redirection always check whether the cookie is not present.

Instructions on setting a cookie:

<script type="text/javascript">
document.cookie="secondpagevisited=43yj0u3jt;path=/"; //execute this line in the head of second page.
</script>

In first page, check for cookie presence:

<script type="text/javascript">
if(document.cookie.indexOf("secondpagevisited=43yj0u3jt")==-1){
    /*do redirection here*/
}
</script>

EDIT: Assuming you control only the first page and not the second page, try this:

<script type="text/javascript">
if(document.cookie.indexOf("secondpagevisited=43yj0u3jt")==-1){
    document.cookie="secondpagevisited=43yj0u3jt;path=/";
    /*do redirection here*/
}
</script>

OTHER TIPS

I gave Ashish the point for putting me on the right track, but this is my solution which goes one step further:

 var s = location.search;
     if(s != '') {
        var split = s.split('?');
         var loc = split[1].replace('?', '');
          if (document.cookie.indexOf('redirected=' + loc + '') == -1) {
             document.cookie = 'redirected=' + loc + '';
             location.href = '' + loc + '';
         } else {
         var url = location.href.replace('' + s + '', '');
         document.cookie = 'redirected=; expires=Thu, 01 Jan 1970 00:00:00 GMT';
         history.pushState(null, null, '' + url  + '');
        }

If the cookie is there, the re-direction doesn't occur, the cookie is removed (in case the user returns to the site that had the original link and clicks it again), and the URL is tidied up by removing the query string.

Thanks for the guidance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top