Return previous page by adding parameter in URL - Javascript

1

Good afternoon person, I'm breaking my head here and could not find a solution. What I need is this.

If a user accesses a url by ex: www.site.com.br/produto it should be redirected to another page with a login type ex: www.site.com/login .

If he is logged in he wanted the user to be redirected to the previous page, however adding the following parameter at the end of the URL: ?id=CS In the example I would then give: www.site.com.br/produto?id=CS

window.location.href = '/?id=CS';

The above code redirects only to the home page, but wanted it to go back to the previous page it tried to access.

    
asked by anonymous 26.07.2018 / 19:44

1 answer

3

Using the document.referrer you have access to the previous page. But remember this command uses the browser information so if you've been redirected from Google.com > your site it will return to Google.com?id=CS

if(window.location.href.indexOf("?id=CS") == -1) {
   window.location.href = document.referrer+'?id=CS';

}
else{
   //não faça nada 
}
    
26.07.2018 / 19:52