Jump to content

pass query string across pages


uworlds
 Share

Recommended Posts

Hello,

How may I take the contents of a cookie and append it to a URL so it is passed to the next page?   The reason is so that its contents are available so a cookie can be made from it (that code already works on the site).

Also, if the page sent to has a URL forward to a different page, can the query string still survive and go all the way to the final destination page?

Kind regards

Edited by uworlds
Link to comment
Share on other sites

If the pages are on the same domain then they should already have access to the same cookies. Trying to preserve a session through query strings alone is very difficult and you can't guarantee that the session key won't be lost somewhere during the user's activity. There is also a security concern where, if somebody copies the URL and sends it to another person then that other person will have access to the same session.

If you just want to direct the user to another page with a query string attached, you can use the location object.

location.href = "somepage?var=value";

If you have a cookie's value stored in a variable (see how to get a cookie's value here) and want to send it in a query string then you can concatenate it to the string, using encodeURIComponent() to prevent malformed URLs.

var cookieValue = "Pretend that this string came from a cookie";
location.href = "somepare?var=" + encodeURIComponent(cookieValue);

 

If you actually want every link on your page to have a special query string attached, it will involve a lot of string manipulation, which is tedious. You will need Javascript to loop through every <a> element on the page (using document.getElementsByTagName("a")), check that the href property belongs to the same domain, then append your value to the query string to the URL and then assign the modified URL back to the link's href property.

Useful string manipulation functions are shown here: https://www.w3schools.com/js/js_string_methods.asp

  • Thanks 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...