Search code examples
javascriptbrowsernotificationsweb-worker

Create notification by webworker


In article about notifications Mozzila says:

Note: This feature is available in Web Workers.

Worker can be created without any warnings

var worker = new SharedWorker('scripts/worker.js');

But when I try to do this inside shared worker:

var notification = new Notification("Hi there!");

It doesn't work. Webworker works fine, it does a XMLHttpRequest, it can read data from main thread and push messages to it but notification doesn't appear. I can't debug it because console is unavailable inside webworker. Permission was granted in main thread and the notifications are also available here.

If it is important I use Chrome 47.0.2526.111 m for developing and debugging. I noticed that Facebook invokes notifications even when FB tab is closed so I am trying to implement something similar.


Solution

  • You are doing something wrong. I had absolutely no problems running notifications in web workers.

    This code works perfectly on jsfiddle:

    Please try following code:

    main.js

    var worker = new SharedWorker("worker.js");
    worker.port.start();    
    Notification.requestPermission(function (permission) {
      // If the user accepts, let's create a notification
      if (permission === "granted") {
        worker.port.postMessage({name:"notification"});
      }
    });
    

    worker.js

    function workerFN() {
      function onmessage(e) {
        switch(e.data.name) {
          case "notification" : 
            console.log("Notification:");
            var notification = new Notification("Hi there!");
          break;
          default:
            console.error("Unknown message:", e.data.name);
        }
      }
      self.onconnect = function(e) {
          for(var i=0,l=e.ports.length; i<l; i++) {
            e.ports[i].addEventListener('message', onmessage);
            e.ports[i].start(); // Required when using addEventListener. Otherwise called implicitly by onmessage setter.
          }
      }
    }
    

    Also console works quite well for me in web workers.