Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 295
Sergei Tsibulchenko Avatar asked Jan 15 '16 12:01

Sergei Tsibulchenko


People also ask

How do I send notifications with a service worker?

For an app to receive push messages, it has to have an active service worker. When the service worker is active, it can subscribe to push notifications, using PushManager. subscribe() .

Can Web Apps send push notifications?

Web Push Notifications are messages that are sent by a website or by a web app to your device, making these notifications significantly visible and also easy to respond to.


1 Answers

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

This code works perfectly on jsfiddle:

  • Worker example
  • SharedWorker example

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.

like image 120
Tomáš Zato - Reinstate Monica Avatar answered Sep 30 '22 06:09

Tomáš Zato - Reinstate Monica