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.
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() .
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.
You are doing something wrong. I had absolutely no problems running notifications in web workers.
This code works perfectly on jsfiddle:
Worker
exampleSharedWorker
examplePlease 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With