Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
Create cookie on closing the browser window or tab

I have a problem. I want to create a cookie in JavaScript and I do it like the following: document.cookie = "type=banner;expires=Thu, 25 Nov 2020 08:50:17 GMT"; Now the problem is that when I close the browser I want this cookie to expire and also to create a new one just like this document.cookie = "type=popup;expires=Thu, 25 Nov 2020 08:50:17 GMT";

How can I achieve the following functionality in JavaScript?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

First of all you can listen for the beforeunload event. This happens "when the window, the document and its resources are about to be unloaded." BeforeUnloadEvent - Web APIs. A cookie can be deleted by setting its expires to zero Document.cookie - Web APIs. And then you can add the new one.

window.addEventListener('beforeunload', e => {
  //"delete" the old cookie
  document.cookie = "type=banner;expires=0";
  //add the new cookie
  var expires = new Date();
  expires.setHours(expires.getHours()+2); // expires in two hours
  document.cookie = `type=popup;expires=${expires.toUTCString()}`;
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!