Skip to content

Instantly share code, notes, and snippets.

@thelinuxlich
Created November 23, 2015 18:47
Show Gist options
  • Save thelinuxlich/b192cf684b98c648b82b to your computer and use it in GitHub Desktop.
Save thelinuxlich/b192cf684b98c648b82b to your computer and use it in GitHub Desktop.
Function for executing logic when closing the page/tab or navigating away
var addUnloadEvent = function(unloadEvent, device) {
// device is a object containing parsed user-agent information
var executed = false,
exec = function() {
if (!executed) {
executed = true;
unloadEvent();
}
};
if (device.type && device.type === "mobile") {
document.addEventListener('visibilitychange', function() {
if (document.visibilityState == 'hidden') {
exec();
}
});
}
window.addEventListener("pagehide", exec);
window.addEventListener("beforeunload", exec);
window.onbeforeunload = exec;
window.addEventListener('unload', exec);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment