Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Service worker for notification on mobile phones #6158

Merged
merged 1 commit into from
Aug 19, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions app/assets/javascripts/channels/user_notification.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ App.room = App.cable.subscriptions.create('UserNotificationChannel',{
disconnected: function(){
},
received: function(data) {
navigator.serviceWorker.register('/sw.js');
// Called when there's incoming data on the websocket for this channel
// Let's check if the browser supports notifications
if (!("Notification" in window)) {
Expand All @@ -12,11 +13,9 @@ App.room = App.cable.subscriptions.create('UserNotificationChannel',{
// Let's check whether notification permissions have already been granted
else if (Notification.permission === "granted") {
// If it's okay let's create a notification
var notification = new Notification(data.notification.title, data.notification.option);
notification.onclick = function(event) {
event.preventDefault(); // prevent the browser from focusing the Notification's tab
window.open(data.notification.path, '_blank');
}
navigator.serviceWorker.ready.then(function(registration) {
registration.showNotification(data.notification.title, data.notification.option);
});
}
}
});
2 changes: 1 addition & 1 deletion app/models/comment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -154,8 +154,8 @@ def notify(current_user)
def send_browser_notification(users_ids)
notification = Hash.new
notification[:title] = "New Comment on #{parent.title}"
notification[:path] = parent.path
option = {
data: parent.path,
body: comment,
icon: "https://publiclab.org/logo.png"
}
Expand Down
20 changes: 20 additions & 0 deletions public/sw.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
self.onnotificationclick = function (event) {
// return clients.openWindow(event.notification.data);
// This looks to see if the current is already open and
// focuses if it is
event.waitUntil(
clients.matchAll({
type: "window"
}).then(function(clientList) {
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
if (client.url == '/' && 'focus' in client)
return client.focus();
}
if (clients.openWindow) {
return clients.openWindow(event.notification.data);
}
})
);

};