I'm working with localStorage and I want to change a counter when closing the page.
I found that onbeforeunload
is the event which can be useful, so I decided to call my function in it. (onunload
doesn't work for me in firefox/chrome)
But when I try to call a function , it doesn't do anything.
Is there any way to call a function when closing/refreshing a tab ?
class MyLib{
constructor(){
window.onbeforeunload = function() {
this._onClosePage();
};
}
_onClosePage() {
let openWindowsCount = this._getItem('countOpenWindow');
openWindowsCount--;
if (openWindowsCount === 0) {
this._clearUp();
}
}
_clearUp() {
this._removeItem('countPagesVisited');
}
}
UPDATE
As suggested by Oday , I fixed the binding. But now , it works randomly.
In chrome, it doesn't catch the refresh event, but sometimes it catches the exit.
In firefox, it catches the exit, and randomly catches the refresh.
class MyLib{
constructor(){
document.getElementsByTagName('body')[0].onbeforeunload = this._onClosePage.bind(this);
}
_onClosePage() {
let openWindowsCount = this._getItem('countOpenWindow');
openWindowsCount--;
if (openWindowsCount === 0) {
this._clearUp();
}
}
_onClosePage() { // call it once the page is closed or refreshed
let openWindowsCount = localStorage.getItem('countOpenWindow');
openWindowsCount--;
localStorage.setItem('countOpenWindow' , openWindowsCount);
if (openWindowsCount === 0) {
this._clearUp();
}
}
_clearUp() {
localStorage.removeItem('countOpenWindow');
}
}