[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2060
  • Last Modified:

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

0
bradley525
Asked:
bradley525
  • 15
  • 11
  • 5
  • +2
1 Solution
 
leakim971PluritechnicianCommented:
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

0
 
bradley525Author Commented:
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
0
 
Randy PooleCommented:
Just remove the expiration date and it turns into a session cookie and will be removed when the browser/session expires..
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
bradley525Author Commented:
I did try that, but when I open the browser back up the cookie information still displays.
0
 
leakim971PluritechnicianCommented:
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

0
 
Randy PooleCommented:
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?
0
 
bradley525Author Commented:
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

0
 
Randy PooleCommented:
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

0
 
bradley525Author Commented:
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.
0
 
bradley525Author Commented:
The rest of the function works..

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

Open in new window

0
 
Randy PooleCommented:
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

0
 
bradley525Author Commented:
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

0
 
bradley525Author Commented:
This failed...It broke the function I am using..


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

Open in new window

0
 
Randy PooleCommented:
You have a control on your page with an id of hodan_current_cookie as well?
0
 
Randy PooleCommented:
Did you you download and reference the cookie extension that I specified?
0
 
bradley525Author Commented:
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..
0
 
Randy PooleCommented:
And you closed every instance of the chrome browser not just the one pointed at your site?
0
 
bradley525Author Commented:
I think this is based on browser settings
0
 
Randy PooleCommented:
It shouldn't be.  Let me try it here, I know it works, I do it all the time..
0
 
bradley525Author Commented:
ok thanks..not sure what else it could be.
0
 
Ray PaseurCommented:
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.
0
 
bradley525Author Commented:
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!
0
 
Randy PooleCommented:
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..
0
 
Ray PaseurCommented:
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.
0
 
mervintCommented:
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"
0
 
bradley525Author Commented:
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.
0
 
bradley525Author Commented:
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.
0
 
Ray PaseurCommented:
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.
http://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:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/A_11271-Understanding-Client-Server-Protocols-and-Web-Applications.html

PHP Sessions:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11909-PHP-Sessions-Simpler-Than-You-May-Think.html
0
 
bradley525Author Commented:
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!
0
 
Randy PooleCommented:
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
0
 
Ray PaseurCommented:
Nope, you can't do it that way.  JavaScript is the wrong tool.  The right way is shown in the article. There are a host of interlocking technologies and security considerations that make JavaScript cookies the wrong thing for server-side client authentication.  As one example of the issues with JavaScript cookies, consider that PHP even has a setting to make cookies invisible to JavaScript!  I can tell you with 100% certainty that this pursuit is like using a wet noodle to drive nails.  Everyone else will choose a hammer (or a nail gun). :-)
0
 
bradley525Author Commented:
Thanks Ray,

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

Thanks!
0
 
Ray PaseurCommented:
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!
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 15
  • 11
  • 5
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now