Send "removeUser" request only on window close and not page refresh - reactjs

I am working on a Chat Application using socket.io/ReactJS. I am facing an issue wherein I need to remove a particular user(String value - Just a username) from the backend(NodeJS/ExpressJS) on Browser window close and not page refresh. As I am using redux-persist(Session Storage) I want to persist the user state when the window is refreshed, but when the user closes the browser window the user will be removed from the backend and obviously from session storage too.
In my App.js file I have below code to register for an event :
removeUserBeforeUnload = () => {
if (window.performance.navigation.type !== 1)
// The socket request which removes the username from the backend
socket.emit("removeUser", this.props.currentUser);
};
setupBeforeUnloadListener = () => {
window.addEventListener("beforeunload", ev => {
ev.preventDefault();
return this.removeUserBeforeUnload();
});
};
componentDidMount() {
// Registering event
this.setupBeforeUnloadListener();
}
I tried using window.performance.navigation.type but that doesn't seem to work.
Thanks for any help.

Related

Google One Tap SignIn Popup not showing

I was trying to implement Google One Tap SignIn in my project. At the first time after building the project the google one tap prompt will display. But next time onwards if we refresh the page also the prompt is not displaying.
Here is my code snippet.
import { addScript } from 'Util/DOM';
/**
* Loads One Tap Client Library
*/
const loadOneTapClientLibrary = async() => {
await addScript('https://accounts.google.com/gsi/client');
}
/**
* Loads One Tap Javascript API
* #param {*} resolve
*/
const loadOneTapJsAPI = (resolve) => {
window.onload = () => {
google.accounts.id.initialize({
client_id: "My client Id",
callback: data => resolve(data)
});
google.accounts.id.prompt();
}
}
export const loadOneTap = async() => {
return new Promise( (resolve, reject) => {
loadOneTapClientLibrary();
loadOneTapJsAPI(resolve);
})
}
After page loads i am calling loadOneTap();
To avoid One Tap UI prompting too frequently to end users, if users close the UI by the 'X' button, the One Tap will be disabled for a while. This is the so-called "Exponental Cool Down" feature. More detail at: https://developers.google.com/identity/one-tap/web/guides/features#exponential_cool_down
I believe you triggered this feature during development. To avoid this, use Chrome incognito mode (and restart the browser when necessary).
As noted by Guibin this is the OneTap exponential cool down feature, it can be easily triggered during development when testing auth flow, but also legitimately when the end user clicks the close icon by mistake. On sites where Google login is optional this might seem pragmatic (i.e. the user genuinely wants to dismiss the popup prompt in favor of alternative login methods), however on a site where Google is the sole login identity provider and you are using the Javascript API instead of HTML api then this can manifest as broken functionality - i.e. no login prompt - and you want to avoid telling your users to use incognito or clear cache/cookies at all costs..
You can potentially handle this with some fallback logic..
window.google.accounts.id.prompt((notification) => {
if(notification.isNotDisplayed() || !notification.isDisplayed()) {
// #ts-ignore
const buttonDiv = window.document.createElement("div")
buttonDiv.setAttribute("id", "googleLoginBtn")
document.getElementsByTagName('body')[0].appendChild(buttonDiv);
// #ts-ignore
window.google.accounts.id.renderButton(
document.getElementById("googleLoginBtn"),
{ theme: "outline", size: "large" } // customization attributes
);
}
This renders a button to login that isn't subject the one-tap cool down feature. We're early days into playing with this so there may be other invariants with regards to state you need to consider (e.g. can isNotDisplayed return true when already logged in) - we already observed some oddities where isDisplayed and isNotDisplayed can both be false on the same invocation of the callback.
Extra note: I recall reading the user can disable all one tap features too, so if you're using the javascript API instead HTML api you will need the fallback to SignIn with Google button.

How to activate a react route and pass data from the service worker?

I have a SPA PWA React app.
It is installed and running in standalone mode on the mobile device (Android+Chrome).
Let's say the app lists people and then when you click on a person it diplays details using /person route.
Now, I'm sending push notifications from the server and receiving them in the service worker attached to the app. The notification is about a person and I want to open that person's details when the user clicks on the notification.
The question is:
how do I activate the /person route on my app from the service worker
and pass data (e.g. person id, or person object)
without reloading the app
From what I understand, from the service worker notificationclick event handler I can:
focus on the app (but how do I pass data and activate a route)
open an url (but /person is not a physical route, and either way - I want avoid refreshing the page)
You can listen for click event for the Notification which you show to the user. And in the handler, you can open the URL for the corresponding person which comes from your server with push event.
notification.onclick = function(event) {
event.preventDefault();
// suppose you have an url property in the data
if (event.notification.data.url) {
self.clients.openWindow(event.notification.data.url);
}
}
Check these links:
https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/notificationclick_event
https://developer.mozilla.org/en-US/docs/Web/API/Clients/openWindow
To answer my own question: I've used IndexedDB (can't use localStorage as it is synchronous) to communicate between SW and PWA, though I'm not too happy about it.
This is roughly how my service worker code looks (I'm using idb library):
self.addEventListener('notificationclick', function(event) {
const notif = event.notification;
notif.close();
if (notif.data) {
let db;
let p = idb.openDB('my-store', 1, {
upgrade(db) {
db.createObjectStore(OBJSTORENAME, {
keyPath: 'id'
});
}
}).then(function(idb) {
db = idb;
return db.clear(OBJSTORENAME);
}).then(function(rv) {
return db.put(OBJSTORENAME, notif.data);
}).then(function(res) {
clients.openWindow('/');
}).catch(function(err) {
console.log("Error spawning notif", err);
});
event.waitUntil(p);
}
});
and then, in the root of my react app ie in my AppNavBar component I always check if there is something to show:
componentWillMount() {
let self = this;
let db;
idb.openDB('my-store', 1)
.then(function (idb) {
db = idb;
return db.getAll(OBJSTORENAME);
}).then(function (items) {
if (items && items.length) {
axios.get(`/some-additional-info-optional/${items[0].id}`).then(res => {
if (res.data && res.data.success) {
self.props.history.push({
pathname: '/details',
state: {
selectedObject: res.data.data[0]
}
});
}
});
db.clear(OBJSTORENAME)
.then()
.catch(err => {
console.log("error clearing ", OBJSTORENAME);
});
}
}).catch(function (err) {
console.log("Error", err);
});
}
Have been toying with clients.openWindow('/?id=123'); and clients.openWindow('/#123'); but that was behaving strangely, sometimes the app would stall, so I reverted to the IndexedDB approach.
(clients.postMessage could also be the way to go though I'm not sure how to plug that into the react framework)
HTH someone else, and I'm still looking for a better solution.
I had a similar need in my project. Using your's postMessage tip, I was able to get an event on my component every time a user clicks on service worker notification, and then route the user to the desired path.
service-worker.js
self.addEventListener("notificationclick", async event => {
const notification = event.notification;
notification.close();
event.waitUntil(
self.clients.matchAll({ type: "window" }).then(clientsArr => {
if (clientsArr[0]) {
clientsArr[0].focus();
clientsArr[0].postMessage({
type: "NOTIFICATION_CLICK",
ticketId: notification.tag,
});
}
})
);
});
On your react component, add a new listener:
useEffect(() => {
if ("serviceWorker" in navigator) {
navigator.serviceWorker.addEventListener("message", message => {
if (message.data.type === "NOTIFICATION_CLICK") {
history.push(`/tickets/${message.data.ticketId}`);
}
});
}
}, [history]);

How to prevent first route to show on notification click in react-native

I have implemented the push notification using react-native-push-nofication here is my push notification configuration.
const configure = () => {
var _token
PushNotification.configure({
onRegister: function(token) {
//process token
//alert(JSON.stringify(token));
Clipboard.setString(JSON.stringify(token))
},
onNotification: function(notification) {
// process the notification
// required on iOS only
navigator.navigate(notification.data.url);
// notification.finish(PushNotificationIOS.FetchResult.NoData);
},
senderID: Config.GCMSENDERKEY,
permissions: {
alert: true,
badge: true,
sound: true
},
popInitialNotification: true,
requestPermissions: true,
});
};
This code is navigating to the desire route successfully but when the application is in background, when user click on notification it shows the root route of the application (splash screen) before navigating to the desire route. I don't want splash screen to show up at all.
I just reviewed the library and I have to say, it's really bad designed. You should move to react-native-firebase.
But if you want to stay with it:
The first thing we have to figure out, is, how we can get the notification with which the app was opened?
We can't use onNotification from the Library, because we don't know when the callback will be called.
The library has a option popInitialNotification which will throw the initial notification with which the app was opened. If you search for this variable in the source code of the library you will find the following:
if ( this.hasPoppedInitialNotification === false &&
( options.popInitialNotification === undefined || options.popInitialNotification === true ) ) {
this.popInitialNotification(function(firstNotification) {
if ( firstNotification !== null ) {
this._onNotification(firstNotification, true);
}
}.bind(this));
this.hasPoppedInitialNotification = true;
}
As you can see, it will call a function named popInitialNotification(callback) with a callback function with the initial notification.
You can now use the function to get the initial notification.
PushNotification.popInitialNotification(function(notification) {
});
With this you have now access to the initial notification directly, without to wait for onNotification.
From here on you can use SwitchNavigator from react-navigation like in the following example: https://reactnavigation.org/docs/en/auth-flow.html

PUT - Web API controller

I have a put method inside my web API controller. The site has a view mode and an edit mode. When the user is in Edit mode it should save the data into the database(because there are currency changes). When the user is on the view mode page it will still calculate the currency changes but it shouldn't be saved into the database.
So inside my method I have a condition in which mode the user is. When it is edit mode it should calculate and save it. When the user is in view mode it only should calculate it and return the object so I can use it client side.
if (isEditMode)
{
_currencyConversionService.ApplyCurrencyRateToCarearRequest(request);
_requestRepository.Save(request);
}
else
{
_currencyConversionService.ApplyCurrencyRateToCarearRequest(request);
}
return Ok(request);
In edit mode the data is saved when the user clicks the confirmation button. But I'm getting an error clientside though:
net::ERR_SPDY_PROTOCOL_ERROR
Is this because I just return the request inside the Ok() that i'm getting this error or why do I get this one? I'm ending up into the catch from this code:
this.service.save(this.model, this.isEditMode)
.then((response: any) => {
debugger;
this.messageService.success('request.notifications.currencySaved');
this.close();
this.$timeout(() => {
this.$window.location.reload();
}, 1000);
}).
catch((reason: any) => {
debugger;
});
How can I return an object inside a PUT method?
Thanks, Brent

SignalR doesn't push message to client

I am implementing functionality to notify the user of long running job completions using SignalR in an AngularJS application.I have created groups of user based on their name,so for each user a group of his name and different connectionids which he has opened up will be created and he would be notified by his group. I want to notify the user on two pages i.e. landing Page and Job Run Page as even if the user is on landing page and job run completes he should be notified of it.
For the same reason i am creating group by his name on both the pages,so that if he is on any page he would be nofied through the group.
On landing page controller js file i have written code to add the user in group as follow...
$rootScope.signalRHub = $.connection.signalRHub;
$rootScope.hubStart = null;
$rootScope.startHub = function () {
if ($rootScope.hubStart == null)
{
$rootScope.hubStart = $.connection.hub.start();
}
return $rootScope.hubStart;
}
$scope.$on('$locationChangeStart', function (event) {
if ($rootScope.userName != "") {
$rootScope.signalRHub.server.leaveGroup($rootScope.userName);
}
});
// Start the connection
$rootScope.startHub().done(function () {
$rootScope.signalRHub.server.joinGroup($rootScope.userName);
});
on Job Run controller js file i have written following code....
$rootScope.signalRHub.client.showNotification = function (message) {
notify('Your notification message');//notify is the angular js directive injected in this controller which runs fine
};
$scope.$on('$locationChangeStart', function (event) {
$rootScope.signalRHub.server.leaveGroup($rootScope.studyid);
});
// Start the connection
$rootScope.startHub().done(function () {
$rootScope.signalRHub.server.joinGroup($rootScope.userName
});
My Hub File.....
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class SignalRHub : Hub
{
public Task JoinGroup(string groupName)
{
return Groups.Add(Context.ConnectionId, groupName);
}
public Task LeaveGroup(string groupName)
{
return Groups.Remove(Context.ConnectionId, groupName);
}
public void ShowNotification(string jobRunDetailId, string userName)
{
if (!string.IsNullOrEmpty(userName))
{
var context = GlobalHost.ConnectionManager.GetHubContext<SignalRHub>();
context.Clients.Group(userName).showNotification(jobRunDetailId);
}
}
}
The issue is when i run the application the group add functionality for both pages works fine.but when i call "showNotification" from Hub it doesn't show any message.
But strange thing is if i comment the "$rootScope.startHub().done...." function on landing page then the jobrun page notify functionality works fine.I am not sure if writing "$rootScope.startHub().done()..." on two places is creating this problem.please help.
You need to wire up all callbacks before calling start. If you turn client side logging on, it'll tell you what hubs you are subscribed to.
Aside:
[EnableCors] is a webapi specific attribute that does not work in SignalR.

Resources