Desktop Notification for ERPNEXT

Hi Guys,
If you need desktop notification, the following can be achieved via this code edit…
pls, note that its not a custom app so you would need to make these changes after very update…

Maybe, someone, can her make it into a custom app on GitHub and help more.

Desktop notification should be shown when system notification is received

  1. This will only work when the site is open on a browser
  2. This will only work when system notification is received (red dot on bell)

Step 1: Create sw.js file in erpnext/public/js folder
self.addEventListener(‘notificationclick’, event => {
const notification = event.notification;
clients.openWindow(notification.data.url)
notification.close();
});
self.addEventListener(‘notificationclose’, event => {
console.log(‘closed’ + event);
});

Step 2: Create desktop_notification.js file in erpnext/public/js folder
function removeTags(str) {
if ((str === null) || (str === ‘’))
return false;
else
str = str.toString();

// Regular expression to identify HTML tags in
// the input string. Replacing the identified
// HTML tag with a null string.
return str.replace(/(<([^>]+)>)/ig, '');

}

function showDesktopNotification(title, body, url) {
Notification.requestPermission().then(function (permission) {
if (permission != “granted”) {
alert(“Notification failed!”);
return;
}

    navigator.serviceWorker.getRegistrations().then(function (registrations) {
        registrations[0].showNotification(title, { body: body, data: {url: url} });
    });

});

}

setTimeout(function () {
navigator.serviceWorker.register(’/assets/erpnext/js/sw.js’);
Notification.requestPermission()

frappe.realtime.on('desktop_notification', (res) => {
    var url = new URL(window.location.href)
    var browser_url = url.origin + frappe.router.make_url([res.document_type.toLowerCase().replace(' ', '-'), res.document_name])
    showDesktopNotification('ERPNext Notification', removeTags(res.subject), browser_url)
});

}, 2500)

Step 3: Add this at the end of erpnext/hooks.py file
def notification_log_after_insert(doc, method):
from frappe import publish_realtime
publish_realtime(‘desktop_notification’, user=doc.for_user, message=doc.as_dict())

Step 4: Add this in doc_events dict in erpnext/hooks.py file
“Notification Log”: {
“after_insert”: “erpnext.hooks.notification_log_after_insert”
},

Step 5: update app_include_js variable in erpnext/hooks.py as below
app_include_js = ["/assets/js/erpnext.min.js", “/assets/erpnext/js/desktop_notification.js”]

Step 6: terminal commands
Bench Build
Bench migrate
Bench restart

May be this help someone in need.

8 Likes