10

I want to set a cookie (using JavaScript or jQuery) to only be sent exactly once.

I can set a cookie with an expiry date say 1 second away just before making the request, but this seems little delicate. I was wondering if there is a way to guarantee that a cookie survives for 1 request, and only one request...

I have had a look through the docs on MDN but con't see anything that fits the bill.

Any Ideas?

JaySeeAre
  • 813
  • 7
  • 22
  • Have you tried removing the cookie via code after the request has been made? – James Donnelly Sep 24 '15 at 09:12
  • Delete the cookie on each page, after you've done your job with it. – George Irimiciuc Sep 24 '15 at 09:12
  • I don't recommend to you that you play with cookies by this mode. It's better if you manage it in the server. Anyway, you can add a cookie and delete it in each request (call function -> add cookie -> finish request -> remove cookie) – Marcos Pérez Gude Sep 24 '15 at 09:12
  • We are using cookies to allow two systems to communicate (one a bit legacy... and i don't have access to the codebase). I can't necessarily guarantee the other site will tidy up my cookies... and if it doesn't then i need to be able to recognize that from the doorkeeper and respond appropriately. A cookie which lasted 1 request seemed like the answer. I know its not perfect - that is why i was hoping for a better solution... – JaySeeAre Sep 24 '15 at 11:36

3 Answers3

0

You could use an AJAX complete handler to remove the cookie after every request.

https://api.jquery.com/ajaxComplete/

$(document).ajaxComplete(function() {
    // delete your cookie
});
0

Here's one way:

  1. Encode the value of the cookie in JSON format, e.g.
var c = {"foo":"bar"}
Cookies.set('test',JSON.stringify(c))
  1. Add to that cookie value a nonce value such as the desired expiration time of the cookie itself, e.g.
var c = {"foo":"bar","expire_time":1612561366588}
Cookies.set('test',JSON.stringify(c))
  1. Expire the cookie once that time has passed, using the standard cookie deletion method on either client or server, e.g.
var c = JSON.parse(Cookies.get('test'))
if (c.expire_time < (new Date()).getTime()) {
  Cookies.remove('test')
}
Klokie
  • 5
  • 2
-2

have a look here :)!
How do I set/unset cookie with jQuery?

In my eyes, there is the answer!

Community
  • 1
  • 1
Sebastian Tam
  • 119
  • 2
  • 8
  • 1
    Thanks, i know i can delete and create cookies but i was hoping for a method to tell the browser to only keep the cookie for 1 request. so that answer doesn't really help. See my reply to the comments on my question. – JaySeeAre Sep 24 '15 at 11:40
  • Specifically this is not safe if CSS/JS/other assets are requested while parsing html, which may occur independent of script execution. – Warlike Chimpanzee May 03 '19 at 16:07