Return previous page by adding parameter in URL - Javascript

Asked

Viewed 235 times

1

Good afternoon, people, I’m racking my brain here and I couldn’t find a solution. What I need is this.

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

If he logs in he wanted the user to be redirected to the previous page, but adding the following parameter at the end of the URL: ?id=CS The example I gave would then be: 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 that he tried to access.

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 have been redirected from Google. > your website it will return to the 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 
}
  • I’ll take a test and I’ll be right back

  • @Fredericomoreira blz

  • @Did Fredericomoreira work out? if yes mark as correct by kindness

  • It worked. Thank you!

  • Leonardo, could you help me with something else. I have the following problem. If the previous url already has ? id=Cs on it, the system is adc another at the end, making the page not open. How could I check the URL before adding? For example, if there is "? id=CS" I would not add anything to the url or add &id=Cs

  • @Fredericomoreira ready, using the indexOf passing the string you want to find inside the url, it returns the index, if it is -1 it means it didn’t find it, take a look at the edition

  • I understood, but in case I need to know if it exists in the URL of Document.referrer which is the previous url we are at the moment. Just change the window.location.href?

  • And there is another problem, imagine that the previous url has another parameter, e.g.: site.com.br? test=1 actually I would need to know if there is a parameter in pq url if there exists I would have to adc was &id=CS or ? id=CS

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.