I am creating a web app using web socket, which on user closes the tab I will make an API call to the server to clean the user related info in the server, I used onBeforeUnload listener in javascript, but this method also gets triggered during the page refresh.
I need to trigger a method only during the tab or browser close, but not during the page refresh.
I know this question has been asked several times, some solution suggested using cookies will not be helpful in my case
navigator.sendBeacon() method can be used for sending data from browser to server when a tab is closed.
Here is an example:
window.addEventListener("unload", function informServer() {
navigator.sendBeacon("/server-api-to-collect-data", my-data)
})
More information:
https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon
As far as I know, you can not listen to actions of browser's tab close or exits. For your application it is an "unload", whatever caused it...
The only thing I could think about is maybe add a listener for keyboard key press (F5), however it doesn't help in case someone refreshed by clicking on the browser's refresh button.
I don't know what is the use case, but most of the things should be done when a page unloads (no matter why) and/or when the page is back up again. So most of the solutions are for situations where your page is loaded again - and then you can determine what was the source of the load and make farther actions, but since you have an option were someone can close and never come back, that might not be the case.
Some solutions for page load up:
You can use Navigation type.
You can check referer.
You can use cookies or other types of browser storage.
I would recommend to rethink about your use case. Maybe you can do whatever you want on load up or leave it on onBeforeUnLoad without knowing the future :)
Related
Bit of background in the problem: I am working on a project that loads most of it's content via api calls in JS. The initial page is built in PHP and delivered ready to use, but every interaction/load after that is just done in JS async and pushed to the "content area" of the html. I'm adding QoL so that you can navigate back to where you were using your history/back/forward button, but in order to do that, every time you navigate using those buttons, I would like to force-refresh the page (for various reasons which I don't think are relevant but am happy to describe if requested).
I'm struggling to understand both pushState and pageShow when used in conjunction. As far as I know, I can use pushState to push new entries to the history object every time it's run, like so:
// Update history
var stateObj = {};
history.pushState(stateObj, response.data.title, uri);
That seems to be working when I run that section of code and check my browser history; a nice neat entry sitting there every time I run it. As far as I know, the title isn't actually supported by any browser, but it doesn't hurt to have it.
My issue occurs when I try to use that newly generated history with the back/forward buttons. As far as I can tell doing some google research, typical browser behavior will not actually reload the page when I press the back button. Herein is where I believe my problem occurs. While navigating to any url fresh will load that specific piece of content into the content area, the site is basically a single page application, loading content into the content area async as it needs it. It doesn't actually change pages. I'm not sure, but I think that is the core problem. I have tried to use several events to "catch" the back/forward behavior:
window.onunload
window.onpageshow
$(window).on("pagehide", function() {})
window.addEventListener("pageshow", function(event) {})
I know several of those are basically the same thing, but I was trying to cover my bases. I have looked around for a solution, and I know that window.onunload is SUPPOSED to override the bfcache (not even sure if that is my problem), but it doesn't seem to fire at all, no matter how many times I navigate between the history.pushState entries. I'm not familiar enough with any of these functions to tell where my problem is. What am I doing wrong?
I am looking to develop a small popup message which acts similar to the window.beforeunload function, to notify the user, that if they leave the current page, they will lose all of their data.
However the issue with the beforeunload event is it fires to often.
I would like to have the popup message fire only when a user closes the page, or clicks a link which takes them away from the current page, to ensure they are aware that their current action will result in the loss of the form data they have entered so far.
However beforeunload event goes further to fire when they refresh the page, which is not needed for this case, and also when the forum is submitted.
Could anyone advise me on the best way to develop this. I thought about using a basic confirm dialog and have it fire under the right circumstances, however is it possible to know if the user is refreshing the page, and if the forum is being submitted (without jQuery).
How can I have this dialog fire at the appropriate times?
Unfortunately, I don't think this is possible. The page unload events are very limited, for security reasons.
If you only want it to appear if the user added or changed formdata, why not check for changes in the data? If yes then return the question on beforeunload, if not do nothing.
Assuming that the form isn't too complicated, you could save form data by using Ajax call, which means there will not be a page reload. So, beforeunload will then behave as it was designed to.
i want to know is there any way we can know browser's events.. like : clicking on BACK button, FORWARD button, REFRESH button by javascript.
These specific browser events are not available as it would be vulnerable to severe privacy violations. Privacy is something browser vendors hold sacred and a key selling (proverbial) point. All browsers allow you to know is when a user enters or leaves your page for which Kamui pointed out the technical details.
Within the same site, it's possible to achieve some browser event tracking using cookies and javascript. For example track wether users click on a hyperlink and label it as a forward event and when a user leaves the page without clicking on a hyperlink it could be one of:
browser url input
back action
javascript location.href replace
The location.href replace can be tracked as well when you have full control over all javascript, just use a helper method with tracking code instead of directly chaning location.href.
That leaves browser url input and the back action. With cookies and request headers (getting the referrer) it is possible to get close to finding out the forward and back events, though not 100%, but pragmatically, 99% sure is good enough.
Figuring out the refresh event is easy with request headers (referrer), if the current url matches the referrrer, it's a refresh event.
Now I offer no code or definite solution, but I outlined what you could do to track back, forward and refresh events within a single domain context. It won't be a quick and easy way to implement it and as far as I know, there's no framework in existance that reliably tracks browser events or even comes close to what I described above.
A more common/lazy technique to achieve something similar is to create a single page app, for which there are many frameworks available. Just google single page app framework, but thats a pretty heavy solution with other implications that I won't go into now.
You can not capture (for example run some piece of code when user presses Back button) them, however, you can direct your pages in history by using:
history.go
history.back
history.forward
More about JS History object.
As #sarfraz says you cannot capture the back and forward button clicks but you could call
window.onbeforeunload = function(){alert("you just tried to leave the page");};
which should be triggered when either the back/forward/refresh buttons are clicked to perform an action, unfortunately you can't tell if they are going back or forward. Please note don't alert a message it's really annoying when trying to exit a page.
EDIT
you can also do this in jQuery if you have it
$(window).unload( function () { alert("Bye now!"); } );
I'm trying to figure out a way I can determine how long a user has been on a page. I'm open to javascript solutions that call some server script periodically, but I'm wondering if there are any better solutions than that?
I've read Can you fire an event in JavaScript before the user closes the window? and it seems useful, but I need to know for certain when the page is closed.
Is there any way I can determine if the page is "active"? (meaning on top of other tabs / windows and the user is paying attention to it? this is for an educational web application)
I don't know how much this will be helpful.
However your problem seems more a browser task then a page task.
If you want to implement a general, client side soltution you could write for example a chrome-extension.
In the chrome.tabs.* api there are all function needed to detect when a page is loaded, active, selected or is closed.
onCreated
chrome.tabs.onCreated.addListener(function(Tab tab) {...}));
Fires when a tab is created.
onRemoved
chrome.tabs.onRemoved.addListener(function(integer tabId, object removeInfo) {...}));
Fires when a tab is closed.
onSelectionChanged
chrome.tabs.onSelectionChanged.addListener(function(integer tabId, object selectInfo) {...}));
Fires when the selected tab in a window changes.
Ended up creating a javascript function which called a php script on the server periodically. Saved the 'last-updated' field in a database and set a minimum time before which it could be updated in order to ensure the polling function wasnt maliciously called by a user.
Once the user is on my page, I do not want him to refresh the page.
Anytime, the user hits F5 or refresh button on top. He should get an alert saying
You cannot refresh the page.
Also if the user opens a new tab and tries to access the same url in prev tab he should get an alert
You cannot open same page in 2 tabs
Anyway I can do this using JavaScript or jQuery? Point one is really important.
#1 can be implemented via window.onbeforeunload.
For example:
<script type="text/javascript">
window.onbeforeunload = function() {
return "Dude, are you sure you want to leave? Think of the kittens!";
}
</script>
The user will be prompted with the message, and given an option to stay on the page or continue on their way. This is becoming more common. Stack Overflow does this if you try to navigate away from a page while you are typing a post. You can't completely stop the user from reloading, but you can make it sound real scary if they do.
#2 is more or less impossible. Even if you tracked sessions and user logins, you still wouldn't be able to guarantee that you were detecting a second tab correctly. For example, maybe I have one window open, then close it. Now I open a new window. You would likely detect that as a second tab, even though I already closed the first one. Now your user can't access the first window because they closed it, and they can't access the second window because you're denying them.
In fact, my bank's online system tries real hard to do #2, and the situation described above happens all the time. I usually have to wait until the server-side session expires before I can use the banking system again.
You can't prevent the user from refreshing, nor should you really be trying. You should go back to why you need this solution, what's the root problem here?. Start there and find a different way to go about solving the problem. Perhaps is you elaborated on why you think you need to do this it would help in finding such a solution.
Breaking fundamental browser features is never a good idea, over 99.999999999% of the internet works and refreshes with F5, this is an expectation of the user, one you shouldn't break.
Although its not a good idea to disable F5 key you can do it in JQuery as below.
<script type="text/javascript">
function disableF5(e) { if ((e.which || e.keyCode) == 116 || (e.which || e.keyCode) == 82) e.preventDefault(); };
$(document).ready(function(){
$(document).on("keydown", disableF5);
});
</script>
Hope this will help!
Back in the ole days of CGI we had many forms that would trigger various backend actions. Such as text notifications to groups, print jobs, farming of data, etc.
If the user was on a page that was saying "Please wait... Performing some HUGE job that could take some time.". They were more likely to hit REFRESH and this would be BAD!
WHY? Because it would trigger more slow jobs and eventually bog down the whole thing.
The solution?
Allow them to do their form.
When they submit their form... Start your job and then direct them to another page that tells them to wait.
Where the page in the middle actually held the form data that was needed to start the job.
The WAIT page however contains a javascript history destroy. So they can RELOAD that wait page all they want and it will never trigger the original job to start in the background as that WAIT page only contains the form data needed for the WAIT itself.
Hope that makes sense.
The history destroy function also prevented them from clicking BACK and then refreshing as well.
It was very seamless and worked great for MANY MANY years until the non-profit was wound down.
Example:
FORM ENTRY - Collect all their info and when submitted, this triggers your backend job.
RESPONSE from form entry - Returns HTML that performs a redirect to your static wait page and/or POST/GET to another form (the WAIT page).
WAIT PAGE - Only contains FORM data related to wait page as well as javascript to destroy the most recent history. Like (-1 OR -2) to only destroy the most recent pages, but still allows them to go back to their original FORM entry page.
Once they are at your WAIT page, they can click REFRESH as much as they want and it will never spawn the original FORM job on the backend. Instead, your WAIT page should embrace a META timed refresh itself so it can always check on the status of their job. When their job is completed, they are redirected away from the wait page to whereever you wish.
If they do manually REFRESH... They are simply adding one more check of their job status in there.
Hope that helps. Good luck.
No, there isn't.
I'm pretty sure there is no way to intercept a click on the refresh button from JS, and even if there was, JS can be turned off.
You should probably step back from your X (preventing refreshing) and find a different solution to Y (whatever that might be).
Issue #2 now can be solved using BroadcastAPI.
At the moment it's only available in Chrome, Firefox, and Opera.
var bc = new BroadcastChannel('test_channel');
bc.onmessage = function (ev) {
if(ev.data && ev.data.url===window.location.href){
alert('You cannot open the same page in 2 tabs');
}
}
bc.postMessage(window.location.href);
Number (2) is possible by using a socket implementation (like websocket, socket.io, etc.) with a custom heartbeat for each session the user is engaged in. If a user attempts to open another window, you have a javascript handler check with the server if it's ok, and then respond with an error messages.
However, a better solution is to synchronize the two sessions if possible like in google docs.