Reputation:
Hey I have this function that works well on both "onbeforeunload" and "onunload" but the only issue is that it works when the browser refreshes. I want to stop it from working only when the browser refreshes. Here is the code:
<script type="text/javascript">
window.onbeforeunload = function() {
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET", "/logout.php", false);
xmlhttp.send();
};
</script>
How can I stop it from occurring when the browser refreshes only?
Upvotes: 0
Views: 221
Reputation: 5223
You want an onload event that run only when the user hasn't been to the page in a while. Why not just run a script that updates a cookie while the page is in user. When the page is loaded check if the cookie hasn't been updated in a while. Why no something like this:
window.setInterval(function(){document.cookie="last_active" + "=" + new Date().getTime();}, 60000);
Then we can get the cookie and test to see if the user is just refreshing the page or if they have been gone for a while
document.onload = function() {
if(document.cookie[last_active] && document.cookie["last_active"] > new Date().getTime()){
whateverScriptYouAreTryingToRun();
}
}
Upvotes: 0
Reputation: 3361
First, you need to capture the unload event and set a cookie:
In your unload handler, set a cookie:
document.cookie="lastUnloadTime=" + (new Date()).toString();
Then, you can check in your onload
handler (by looking at the value of document.cookie
) to see (a) if the session cookie is present and (b) if you last exited within a short interval of time.
Upvotes: 1
Reputation: 4278
You can use session storage and set a flag value in it to determine if the page has already been loaded. But keep in mind the rules surrounding local storage and the fact that the value will remain set until you close the broswer and reopen it.
Upvotes: 0