2

When I close the browser, I want to remove cookies. How can I do this? i use th bibliotek angular2-cookie.

rachedbch
  • 41
  • 2
  • 7

1 Answers1

3

The onbeforeunload event will allow you to run some code before the user leaves the page. Combining that with the code from this answer will allow you to clear all the cookies when the user tries to leave the page.

window.onbeforeunload = function (e) {
  deleteAllCookies();
}

function deleteAllCookies() {
    var cookies = document.cookie.split(";");

    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[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";
    }
}

In relation to angular 2, if this is a one-off thing, it's totally fine to put it in your index.html page as a bottom snippet, because it's not really related to your Angular 2 application. If you want to do it in Angular 2 fashion, you should be able to put this in your AppComponent.

@HostListener('window:onbeforeunload', ['$event'])
onBeforeUnload() {
    this.deleteAllCookies();
}

deleteAllCookies() {
    var cookies = document.cookie.split(";");

    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[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";
    }
}
Community
  • 1
  • 1
Adam
  • 4,445
  • 1
  • 31
  • 49
  • thank's, there is some things else. how to make an only secure connections? – rachedbch Apr 02 '17 at 08:42
  • 1
    What do you mean? That sounds unrelated to this question, maybe you should try asking a new question, or searching SO for the answer. – Adam Apr 02 '17 at 16:41
  • 1
    @rachedbch, also, it's good form on Stack Overflow to accept an answer, to say it's the correct one, to help out other people who find this question in the future. – Adam Apr 02 '17 at 16:43
  • Adam, thank's for the answer. This is what i search. – rachedbch Apr 03 '17 at 08:17