Sending a browser notification

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.


if (window.Notification) {
  .then((permission) => {
    if (Notification.permission === "granted") {
      new Notification("WSF", {
        body: "New newsletter uploaded"


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.

1 Like

Thanks @Dormilich. I’ll see if I can do that…

If you are uploading via AJaX, then the trigger would lie within the .done().


^ _ ^

I’m just using PHP for the file upload.

I think I have some sort of idea.

  • JS connects to a web socket server
  • WSS waits for a message
  • when it receives message it sends a reply which is caught by the JS which fires off the Notification

but I’m still not sure how to get the initial message to the socket server once the file has been uploaded.

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:

1 Like

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! :slightly_smiling_face:

So I shall have to look up the latter now.

Thanks @m3g4p0p

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.