简体   繁体   中英

Clear Session Cookie in Browser Programmatically

How can I clear a session cookie that resides in the browser memory programmatically, preferably using javascript?

Since it's a session cookie and doesn't have an expiry date, setting the expiration date in the past will not work like it does for a persistent cookie.

I have a current session for our website, but we have an iframe that connects to another site. This site creates a session cookie. I would like to clear their session cookie without effecting ours. I can do it in Firefox via the clear cookies option, but I need to do it programmatically.

Thanks


I never did try the following method of deleting cookies since I read that session cookies don't have an expiration date, but here's what I've found. Will this work for reseting the session cookie? I know this deletes all cookies, but I could modify it.

function deleteCookies() {
   var allcookies = document.cookie.split(";");

   for (var i = 0; i < allcookies.length; i++) {
        var cookie = allcookies[i];
        var eqPos = cookie.indexOf("=");
        var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
        document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    }
}

Read about Same-origin policy

In short, if the iframe is loaded from a different domain of the page where your JavaScript runs, then you cannot have access to the cookie. This is security restriction.

If the iframe is the same domain and as the page with your JavaScript, then you can remove the iframe's cookie by chaning the expiration date or assign to it empty value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM