Created
November 23, 2015 18:47
-
-
Save thelinuxlich/b192cf684b98c648b82b to your computer and use it in GitHub Desktop.
Function for executing logic when closing the page/tab or navigating away
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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