Manoj Kumawat

Manoj Kumawat

  • 0
  • 185
  • 1.4k

Manage multiple browser tabs in signalr

Jan 2 2017 4:41 AM

I am developing a chat application like facebook in MVC 4.

I am connecting to hub like following

var chat = $.connection.chatHub;
$
.connection.transports.longPolling.supportsKeepAlive = function () {
 return false;
}
$
.connection.hub.qs = "UserID=" + $('#hdfLoggedInUserID').val();
$
.connection.hub.start().done(function () {
//...
});
$
.connection.hub.disconnected(function () {
 setTimeout
(function () {
 $.connection.hub.start();
 }, 5000); // Restart connection after 5 seconds.
});

And my hub class is like following

 public override Task OnConnected() 
{
var userID = Context.QueryString["UserID"];
if (userID != null)
{
//set user online in database and save connection_id
RefreshOnlineUsers(uId);
}
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
var userID = Context.QueryString["UserID"];
if (userID != null)
{
//set user offline in database RefreshOnlineUsers(uId);
} return base.OnDisconnected(stopCalled);
}

It's working fine when I am working with only one browser tab.

OnConnected calls when browser tab open and OnDisconnected calls when browser tab closed. So according to this when I open one tab then OnConnected calls and user's status(online) and connection_id update in database.

After that I open my application in new tab of same browser then OnConnected method calls again and user's new connection_id and status(online) update in database.

After that when I close new browser tab then OnDiconnected calls and user's status changes to offline in database. But user is still online in previous browser tab.

Due to this issue this user is offline according to database but it's online.

I am already done lot of R&D about it but can't find any proper solution.

Q : How can I resolve this multiple browser tab issue?

Thanks.


Answers (1)