unload event
HTML
<p>
When you click <a href="https://google.com">this link</a>, or close the window, an alert box will be triggered
</p>
JavaScript
document.cookie = 'test=1; expires=0; path=/';
window.addEventListener('unload', function () {
console.log('unload');
document.cookie = 'test=;expires=Thu, 01 Jan 1970 00:00:01 GMT';
});