How do I detect when a user closes their browser? - javascript

I am trying to set something up in my application so that I can detect if two users are editing the same document at the same time. The best way I could think to do this was by sending information to the backend when a user logs in and logs out, and checking that when I want to see if two users are active at the same time. Starting the application is easy to detect with useEffect, but I'm having trouble finding a way to do so cleanly.
I looked at the onunload and onbeforeunload, but those don't seem to have universal browser support, and I'd prefer to not disrupt the user experience with a popup. I was thinking about checking for idle, but if there's a cleaner method, such as something with Google Cloud Platform, that would be helpful. Thanks!

That sounds like a great use case for onDisconnect. You can read more about it here and here.
This would be a simple example:
var ref = firebase.database().ref("onlineState");
ref.onDisconnect().set(false);
What happens here is that this command is send to Firebase and lives there. When you lose connection to Firebase it will be executed. It doesn't matter if it's done by closing the browser/tab etc...
If you need a more complex code execution then attach a firebase cloud function trigger to those changes. It's importand to know that you can't execute client side code on that event.

Related

Custom web page and javascript routine running in the background

The Dynamics documentation is just awful and I couldn't find an answer to this simple question:
In the web version of the CRM, is it possible to register a web page that can be toggled by the user and that itself has an internal state (updated regularly by an interval set with setInterval) that will persist even if the users closes the page (not the entire CRM, just the sub-page)?
We need the user to provide some information for a CTI integration, and this background process to keep alive the CTI session by polling an API while the user session is active. In addition, we need to reuse the component where the user provides the CTI information to be notified if the session fails and restore it or close it if necessary. The real purpose for this is to make a screen pop (push content information about the incoming call to the agent) which I know can be done using Xrm.Utility, although doing it with a REST API method would be much better, RouteTo Aciton looks like the best method to do this, but I'm not sure it will proactively show the item in the user's browser.
I'm not sure this question is as simple as you suggest, it seems relatively complicated, and involves an integration. I'm not suprised the Dynamics documentation doesn't provide an answer for this specific and unique scenario.
I don't believe there is any single feature within Dynamics that will meet this requirement.
You could use a HTML web resource or a web page from a seperate web site iframed into CRM. I think the possible use of these depends on your expected user experience; I believe the user would need to have the page loaded at all times showing these controls (e.g. user is looking at a dashboard) - I don't see how the controls could interact with the user client side otherwise. You could show the controls in multiple places however.
Xrm.Utility is one way to open a record, but it can also be done by Open forms, views, dialogs, and reports with a URL.
RouteToAction looks like it just adds a record into the user queue, the user would need to refresh the queues to see the changes. I don't believe there is any way for a server side REST API call to natively redirect the user.
You could add JavaScript to do this, however you might struggle to add the JavaScript into every page of CRM.
Where I have worked on a CTI integration in the past (assuming you mean computer telephony integration), we always had some other component doing the screen pops - the client's all had a desktop app installed as part of the telephony solution.
Perhaps you could look into browser notifications, or a browser plugin?

How to logout user after disconnect or browser close?

I'm trying to work a solution to timing out a user from my web application. I'm currently using ng2-idle and it seems to only work on the active window rather than be tracked server side (angular server webpack)
I need to handle these two events in addition to the one above:
On Browser Close
On Connection loss (Power cut, blue screen, etc..)
After testing, my timeout was not being tracked after closing the window. Ng2-idle has modules such as keepalive but I'm not exactly sure how to use it and if it solves my problem
I will provide code if needed
thank you
The main problem is, that the client and server are communicating in stateless manner. This means if the user disconnects no body knows.
If your browser has a hook function for closing or navigating to another site you could use that and send the logout request.
Another thing which relavant is session expiration, you should use that. If you are using a token you will need to blacklist that, as non active as long as the session may be valid (or however).
Disconnect is a major problem (session expiration tried to solve that somehow).
A more sophisticated way if it is really crucial to log out on disconnect you may need to use websockets or http long polling. You would need to send a heartbeat and if it's not responding, after some time you will automatically logout the user.
Hope these thoughts kind somehow help.
when you close your browser session will destroy.So you can use session to logout.

How to manage connexion with IndexedDb in Single Page Application

I'm trying to understand how to work properly with IndexedDb and one thing I can't understand is how are we supposed to manage the connection.
When I started playing with IndexedDb, I created a connection once the page is loaded and let it open. So the same connection was used with every request to the database until the page was reloaded.
Letting a connection open seemed like a bad practice (which is what I want to confirm) so I changed my code to open the connection only when needed (when retrieving data for example) and close it immediately after.
It doesn't feel like the API was supposed to be used that way as I felt like fighting it when modifying my code (which might simply be because I have not yet fully understood how to work with it).
Can someone please explain to me the best practice when working with IndexedDb ?
I don't really have a best practice about it, but when you are working with databases on a server you mostly close the connection when the action is completed, and you open one for every action you want to do. In the library I builded to wrap the indexedDB I also choose to open and close the db connection for every action. That way I'm sure that no connections stay open, and it gives me the flexibility to change the db structure without having to worry about all the open connections.
What are the issues you are suffering with when opening and closing the db connection for every call?

Onunload, onbeforeunload - guidance requested

I have a web server that generates questions for students of a particular subject. The web server needs to keep track of how much time each student has spent on a particular set of questions.
The web pages have a "Finished" button, which, when pressed, causes statistics to be sent to server.
However, I also want the web browser to send statistics if the student navigates away from the page or closes the browser window without pressing "Finished".
For this purpose, I have planned to have "onunload" or "onbeforeunload" send an Ajax request to the server with the relevant information. But apparently different browsers do not fully support these events, and also there are restrictions on what can be done in the event handlers. And, of course, I don't want the browse to freeze if the communication with the server fails.
So, I need some advice on the best way to do this.
If I wanted to be sure to handle all the "special events" I would send tick 'requests' from the webpage to the server. Granularity depends on the tracking requirements, the load, and whether it is an intranet or internet application; can be some seconds or even a minute. So you are tracking the time spent on the page even if the browser/os/network crashes.
The best way to implement is, is to use period updates. This will pretty much guarantee you have some relevant data when the user disconnects in any way.
An implementation is pretty trivial, all tough you might have to refactor some of your logic to send out period updates instead of everything at once.
function sendStatistics()
{
// ajax and what not
}
setInterval(function(){
sendStatistics();
}, 1000);
An other way to make it work is to make your ajax call in beforeunload and make it synchronous. This will freeze the browser for duration of the call, and will also only work when navigating away or closing the browser, i don't recommend this.

How to sync with server and clear session before the user leaves a page?

Is there any way to detect when a user leaves a page, no matter if it's by closing the browser, entering a new URL in the address bar, clicking on a link that redirects to other domain, etc. ?
The main purpose of this would be to perform some activities such as:
sync with the server some data that resides in the client side
clear server session
I was trying with the window's unload and beforeunload events, and reading other questions like:
Best way to detect when a user leaves a web page?
//
Is there any way to know that user leaving a page with asp.net? but I didn't find the answer I would expect.
Here is a simplified js snippet to understand what I was trying:
window.onunload = function(){
if (theConditionThatINeed){
doThings();
SyncWithServerAndAbandonSession(url, localObjects);
}
else {
doNothing();
}
}
I don't want to display any kind of confirmation before the user leaves, so I think that the onbeforeunload won't help me here.
Supposing that the answer is "there is no way to do such thing", what would be the recommended practice to accomplish the synchronization and session clearing that I want?
The primary browser that I support is IE >= 7
As you already read, it is not reliably possible to detect whether the user leaves your page.
Generally it is not good practice to store any unsynced state on the client side. Browsers are easily closed or crashed.
You can send yourself ajax keepalive messages via javascript, in case the user does anything on your page. Again, very unreliable, wasteful and hacky.
Auto-Sync after a short timeout.
Take a look at RESTful web applications. The concept is interesting, and, very superficially spoken, discourages keeping state information on the server. You can apply this to the client as well.
This usually results in keeping state information in the URL. The URL tells the server anything it needs to know to service the request, it should not need a memory (the session) of any previous activity.
I try to only keep the user identification info in the session. I would get rid of this too, but some tools and libs need the user in the session.

Categories