I want to send a browser notification when a new document is uploaded. My JS sends a notification fine, but I’m not sure how to trigger it in my PHP code.
TheJS
if (window.Notification) {
Notification.requestPermission()
.then((permission) => {
if (Notification.permission === "granted") {
new Notification("WSF", {
body: "New newsletter uploaded"
});
}
});
}
The PHP
if ( is_uploaded_file($tmp_name) && move_uploaded_file($tmp_name, $destpath) ) {
echo '<p>File ', $filename, ' has been uploaded successfully as ', $newfile, '.</p>', PHP_EOL;
//trigger notify.js
}
The Notification API only works via JavaScript. So you cannot trigger it directly from PHP. However, if you can send a push message from PHP to JS (e.g. through Web Sockets), then JS can alert the user through the Notification API.
So every user should get notified when a new newsletter got uploaded (as opposed to just a success message for the one who uploaded the newsletter)? I don’t think web sockets are enough then – the user would have to have a tab with your site opened, which seems rather impractical for a relatively infrequent event like a newsletter (like, once a week or even month).
What you need is push notifications; this works by registering a service worker, which can then subscribe to a certain push service. This worker will run in the background regardless of whether the user is currently browsing your page, or even has the browser opened at all. This is a fairly complex topic, but you can read an excellent introduction here:
Ah, I think you’re right and I’m getting browser notifications and web push notifications mixed up. Having just read how to do the former I thought I’d look for somewhere to use them!