0

I am trying to delete a cookie on page refresh but I am unable to achieve it. I have done this so far

//delete the cookie on page refresh
window.onunload = unloadPage;
function unloadPage()
{
    $.removeCookie('count', { path: '/' });
}

This code is at the top of my js file. I have also tried answers here at stackoverflow

UPDATE I am using laravel and I am using this code to set the cookie

$response->withCookie(cookie()->forever('count', $count));
Community
  • 1
  • 1
StealthTrails
  • 2,281
  • 8
  • 43
  • 67
  • 1
    And do you have a plugin called `removeCookie` ? – adeneo Dec 07 '15 at 23:15
  • yes, https://cdnjs.com/libraries/jquery-cookie @adeneo – StealthTrails Dec 07 '15 at 23:24
  • I suspect you're having trouble deleting the cookie in javascript because it's set to httpOnly. You can check easily in the chrome inspector on the resources tab. There will be a check mark in the HTTP column of the cookie list. – Lea Dec 08 '15 at 00:10

3 Answers3

1
document.cookie = 'count=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
Jeton
  • 44
  • 7
1

So, I had to go this way to delete the cookie

//delete the cookie on page refresh
    $.ajax({
        url:'remove-cookie',
        method:'post',
        success: function(){
            console.log("cookie deleted");
        }
    });

and in my controller method

/**
     * delete the count cookie
     */
    public function destroyCookie(){
        $cookie = Cookie::forget('count');
        $response = new Response($cookie);
        $response->withCookie($cookie);

        return $response;
    }

Route is

Route::post('remove-cookie', 'DonnerController@destroyCookie');

I hope it may help someone working with laravel.

StealthTrails
  • 2,281
  • 8
  • 43
  • 67
0

You don't need to use the unload event, because every time you refresh, every script that is included in your header will be executed from top to bottom.

Because of this, all you have to do is make a simple check at the top of your script, to verify that the current URL is the same as before, if you want to make sure that the page really was refreshed.

Here's an example (not tested):

if (document.referrer == window.location.href) {
    // The page was refreshed.
}

Hope this helps!