Link to home
Start Free TrialLog in
Avatar of bradley525
bradley525

asked on

Clear Cookie using JavaScript when browser is close

Hello I am using the following code to clear a cookie when my browser closes, the only problem is that it clears the cookie when I navigate to another page.

Is there a way to only call the function if the browser closes?


$(window).on('beforeunload', function(e) {
return "You will now be logged out,";
});

$(window).on('unload', function(e) {
document.cookie = 'hodan_current_cookie=; expires=Fri, 3 Aug 2012 20:47:11 UTC; path=/'
});

Open in new window

Avatar of leakim971
leakim971
Flag of Guadeloupe image

use a user session, for example wih PHP, the FIRST LINE OF YOUR PAGE :

<?php
// NO OUTPUT TO THE BROWSER BEFORE THIS LINE
session_start();
$_SESSION["hodan_current_cookie"] = "foo";
?>
<!-- somewhere in your page if you need to check cookie value : -->
<div><?php echo $_SESSION["hodan_current_cookie"]; ?></div>
<input type="text" value="<?php echo $_SESSION["hodan_current_cookie"]; ?>" id="session_cookie" />
<input type="hidden" value="<?php echo $_SESSION["hodan_current_cookie"]; ?>" id="session_cookie_hidden" />

Open in new window

Avatar of bradley525
bradley525

ASKER

Thanks, but that is not what I am looking for ...I am looking for a javaScript or jQuery function that will know when the browser is closing and will then clear a cookie..

Thanks
Just remove the expiration date and it turns into a session cookie and will be removed when the browser/session expires..
I did try that, but when I open the browser back up the cookie information still displays.
how are you mooving to this another page? entering a new url? or click on a link? if it's by clicking on a link, attach an event to this link or button to say don't clear the cookie

$("a.outside,button.outside").click(function() {
    window.dontclear = true;
});

$(window).on('unload', function(e) {
  if(window.dontclear) return; // don't clear
  // else clear :
  document.cookie = 'hodan_current_cookie=; expires=Fri, 3 Aug 2012 20:47:11 UTC; path=/'
});
   

Open in new window

You removed the expiration date from where you set the cookie initially?  Also did you have all windows closed for the browser you are testing with?
So here is the javaScript I am using


var hcc = $('#hodan_current_cookie').val();	
		document.cookie = 'hodan_current_cookie='+hcc+';UTC; path=/'

Open in new window

Just to be sure, remove the UTC parameter, who knows what the browser may try to set when an unknown parameter is being passed.
var hcc = $('#hodan_current_cookie').val();	
		document.cookie = 'hodan_current_cookie='+hcc+';path=/'

Open in new window

It seems to work in  IE, but not in Chrome, also the rest of the function after setting the cookie fails to run too when I do not have an exp date.
The rest of the function works..

Leaving off the exp date only works in IE...
you are missing a ; at the end of the statement
document.cookie = 'hodan_current_cookie='+hcc+';path=/'

Open in new window

You may also want to use the jQuery cookie plugin.
https://github.com/carhartl/jquery-cookie
then
set
$.cookie('hodan_current_cookie',$('#hodan_current_cookie').val(),{path:'/'});

Open in new window

remove
$.removeCookie('hodan_current_cookie');

Open in new window

query
var ck=$.cookie('hodan_current_cookie');

Open in new window

No I can no longer set the follow cookie..It just show up blank every time.

var hcc = $('#hodan_current_cookie').val();	
document.cookie = 'hodan_current_cookie='+hcc+'; expires=Thu, 21 Aug 2014 11:58:20 UTC; path=/'	

Open in new window

This failed...It broke the function I am using..


$.cookie('hodan_current_cookie',$('#hodan_current_cookie').val(),{path:'/'});

Open in new window

You have a control on your page with an id of hodan_current_cookie as well?
Did you you download and reference the cookie extension that I specified?
Ok I got the jQuery Cookie plugin working..That works...I used


$.cookie('hodan_current_cookie',$('#hodan_current_cookie').val(),{path:'/'});

Open in new window


Then closed out the browser and when I reopened the browser the cookie was still there..
And you closed every instance of the chrome browser not just the one pointed at your site?
I think this is based on browser settings
It shouldn't be.  Let me try it here, I know it works, I do it all the time..
ok thanks..not sure what else it could be.
I am looking for a javaScript or jQuery function that will know when the browser is closing...
As I understand it, you want to have the cookie disappear when the browser is closed, but you have added the stipulation that the browser might have been directed to another "page" before closing.  This strikes me as counter-intuitive and possibly unworkable.  Here is my thinking.

The browser executes JavaScript based upon the content of the document (the HTML, CSS, JavaScript and data in the web page).

When the browser navigates to a new page, it will load and use a new document, containing new JavaScript.

It follows that the JavaScript from the original document will be replaced with the JavaScript from the new document, and the new JavaScript may not be under your control.

If you can tell us what you are trying to achieve, from a high-level non-technical viewpoint, we may be able to suggest a well-understood design pattern.
Hi Ray,

When I close the browser I need the cookie to be removed. With the code I had show above initially it asked me every time I wanted to navigate away from the page. ie. navigate to a new page or close the browser. It would clear / remove the cookie everytime I would navigate away from the current page.

Overall, I just would like to have the cookie removed when the browser is closed..

Thanks!
I verified that the cookie is removed in chrome.  Are you actually looking at the cookies in chrome under
settings->Advanced link->Privacy->Content Settings->All Cookies and site data
before you navigate back to your page to see if the cookie is gone? I have a strange feeling you are adding it again before you check to see if it has been removed..
from a high-level non-technical viewpoint
I get the technical details about cookies and all of that.  What I want to learn is why?  What is the business reason that you want this?

I'm asking because it's a question that is completely new to me -- I've never heard of anyone with a requirement for anything like this.  And it leads me to believe that you must have some motive that is not obvious.  This question never comes up in the normal course of web development.
Things to do when a browser close can only be done in browser preferences

If you want to have that in a page  try beforeunload Instead of on unload
This happens when that window or tab is closed or refreshed
 $(window).bind('beforeunload', function(){

}
If you want to alert a message use return "A message"
Hi Mervint,

I did try this, but it causes issues when you navigate to another page. It always pops up an alert asking if you are sure you want to navigate away from this page.
Hi Ray,

He have developed a login system using Cookies and Session variables. If we close the browser we want the cookie to delete it self so that the user will not automatically be logged back in.
Ahh, now I understand!  Set the cookie life to zero. That is all you have to do.  That is what the PHP session handler does by default.  The normal way of setting a logged-out state is to set the cookie life to some time in the past.

If you want to learn the general design pattern for PHP client authentication, this article covers all of the basics.  If you're using a different scripting language (not PHP) you may have to interpolate a bit, but the principles are the same.
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_2391-PHP-login-logout-and-easy-access-control.html

After you read that article you may have some questions about the "deep background" surrounding HTTP client-server protocols and PHP sessions.  These two articles may help with those questions.  And of course, please feel free to post back if there is anything you do not understand in the articles.  I'll be glad to clarify!

HTTP:
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/A_11271-Understanding-Client-Server-Protocols-and-Web-Applications.html

PHP Sessions:
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11909-PHP-Sessions-Simpler-Than-You-May-Think.html
Hi Ray,

I understand how to clear the Cookie by setting it to 0 or a time in the past..I am trying to call a JavaScript function when the browser closes to do this...

If I use beforeunload it pops up an alert every time I navigate to a different page with in the application. I just want it to trigger when I close the browser..Is there a way to do this?

thanks!
Bradley I made a quick test page.  What it does is checks for the existence of a cookie, if it exists it displays the value.  If it doesn't it allows you to set a value. After doing this, navigate around, when you come back the cookie should still be set.  The close chrome (all instances)  come back to the page and the cookie should no longer have a value.
https://demo.hrweb.com/test/cookie.html
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks Ray,

I am following the guidelines in your article..It is very helpful and I will be modifying my login script.

Thanks!
Thanks for the points.  If you find anything about the article that needs improvement, please post a message to the article and I'll be glad to fix it up!