通过 webworker 创建通知
Create notification by webworker
在 article about notifications Mozzila 中说:
Note: This feature is available in Web Workers.
可以在没有任何警告的情况下创建 Worker
var worker = new SharedWorker('scripts/worker.js');
但是当我尝试在 shared worker 中执行此操作时:
var notification = new Notification("Hi there!");
没用。 Webworker 工作正常,它执行 XMLHttpRequest
,它可以从主线程读取数据并向其推送消息,但不会出现通知。我无法调试它,因为控制台在 webworker 中不可用。权限已在主线程中授予,通知也可在此处获得。
如果它很重要,我使用 Chrome 47.0.2526.111 m
进行开发和调试。我注意到即使 FB 选项卡关闭,Facebook 也会调用通知,所以我正在尝试实现类似的东西。
你做错了什么。我绝对 没有问题 运行 网络工作者的通知。
此代码在 jsfiddle 上完美运行:
请尝试以下代码:
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.
}
}
}
控制台在 web workers 中对我来说也很好用。
在 article about notifications Mozzila 中说:
Note: This feature is available in Web Workers.
可以在没有任何警告的情况下创建 Worker
var worker = new SharedWorker('scripts/worker.js');
但是当我尝试在 shared worker 中执行此操作时:
var notification = new Notification("Hi there!");
没用。 Webworker 工作正常,它执行 XMLHttpRequest
,它可以从主线程读取数据并向其推送消息,但不会出现通知。我无法调试它,因为控制台在 webworker 中不可用。权限已在主线程中授予,通知也可在此处获得。
如果它很重要,我使用 Chrome 47.0.2526.111 m
进行开发和调试。我注意到即使 FB 选项卡关闭,Facebook 也会调用通知,所以我正在尝试实现类似的东西。
你做错了什么。我绝对 没有问题 运行 网络工作者的通知。
此代码在 jsfiddle 上完美运行:
请尝试以下代码:
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.
}
}
}
控制台在 web workers 中对我来说也很好用。