I would like to delete my cookie in visualforce using Javascript based on the delid.

This is what I've tried so far:

 function deletecook() {
  date = new Date();
  date.setDate(date.getDate() -2);
    document.cookie = "id=" + '{!delid}' + "; expires=" + date;

<apex:commandLink action="{!delete}" rerender="thePageBlock" onClick="return deletecook();">
                            <apex:param assignTo="{!delid}" value="{!acc.id}"/>


However, the delid of the cookie does not get deleted. Is there any way I could delete the cookie by the id? Thank you.


This question is kind of off-topic, but the correct format would be:

document.cookie = '{!delid}=; expires=1970 Jan 01 00:00:00 GMT';

Specifying id={!delid} specifies that you want to manipulate a cookie named id, setting it to {!delid}.

There's no need to specify an expiry date that's relative to "now", just use the traditional Unix epoch.

Furthermore, actually, deletecook() won't work the way you expect, because onClick occurs before the re-render takes place. You'll probably want to use onComplete.

Edit: Just do this:

<apex:commandLink rerender="thePageBlock"
 onClick="document.cookie='{!acc.id}=; expires=1970 Jan 01 00:00:00 GMT'" />
  • thanks! Yes I would like to specify id={!delid} so that it will delete that specified id. Can I just clarify if I were to set the cookie on my controller and delete in visualforce Javascript will it take effect? Because right now I tried deleting, but the cookie keep reappearing on refresh – fb69 Mar 13 '15 at 16:49
  • Cookies don't have IDs, they have names. The structure of a cookie is name=value, so if you want to delete a cookie named fubar, by example, you would call document.cookie="fubar=; expires=1970 Jan 01 00:00:00 GMT". Let me add some more code... – sfdcfox Mar 13 '15 at 16:53
  • Yeap name=value. But on page refresh the cookie it still there.. :'( Btw I implemented the cookie using this developer.force.com/cookbook/recipe/… Weird how on page refresh the cookie is still there. – fb69 Mar 13 '15 at 17:04
  • @fb69 If I recall correctly, Apex Code managed cookies are protected from JavaScript via HttpOnly, and also prefixed with some value (apex__). This means your script can't delete a cookie set by the controller. Only the controller can delete that cookie, and controllers can't access cookies that don't start with apex__. You can only delete cookies you create in JavaScript. See Cookie for more info. – sfdcfox Mar 13 '15 at 17:13

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.