-1

Is it possible to set a cookie value, as the url page path?

i.e I have a cookie that is set when someone clicks a button with the ID mybtn but I'd like the value of the cookie to be automatically generated based on the last part of the page path. For example if the user clicked the button whilst on a page www.myweb.com/cars/car1 the value of the cookie should be set as car1. The code below is where I've got to so far, but it's the "THEPAGEPATH" where I'm stuck as I guess I need to use javascript to pull the url information.

<script>$("#mybtn").bind("click", function() {
    document.cookie="model=THEPAGEPATH;path=/;"
});</script>
Wang Liang
  • 4,244
  • 6
  • 22
  • 45
  • Is this answers your question? https://stackoverflow.com/questions/22266227/cookie-accessible-only-by-specific-url – Afshin Mobayen Khiabani Mar 25 '21 at 22:01
  • 1
    sadly not Afshin, that's restricting the cookie to a specific url...I'm happy that the cookie is available on the whole domain, but I want to populate the cookie value based on part of the URL the user was on when they clicked. – Matt Cooper Mar 25 '21 at 22:03

1 Answers1

1

Simple solution would be to just split the string, and take the last part of it.

<script>$("#mybtn").bind("click", function() {
  const strings = window.location.href.split("/").filter(str => !!str)
  document.cookie=`model=${strings[strings.length - 1]};path=/;`
});</script>

This works for both routes with and without trailing slash. It does not work for routes that have query parameters that contains slashes. If you need to support that, you could split the string on ?, and the use the same logic on the first part of the string.

Stephan Olsen
  • 1,623
  • 1
  • 14
  • 29
  • Just a thought Stephan, where some of the models have spaces, the url of course changes spaces for dashes e.g. my-car-test can I get the cookie to replace the dash so that I have spaces? – Matt Cooper Mar 25 '21 at 23:46
  • You can do that with the [replaceAll](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) function. – Stephan Olsen Mar 26 '21 at 07:25
  • Hi Stephan, from my research I think I came across the same answer, but for some reason I can't get it to work...do I use the replaceAll in the same script that you provided? i.e before it sets the cookie? – Matt Cooper Mar 26 '21 at 07:44
  • this is what I tried, but it's not setting the cookie at all now: – Matt Cooper Mar 26 '21 at 07:52
  • `replaceAll` can only be called on strings. The `strings` variable is actually an array of strings, in this case we're just only interested in the last item in the array, as that is what corresponds to the last part of the url. You need to call the `replaceAll` function on the string, rather than the array of strings. – Stephan Olsen Mar 26 '21 at 14:22