即使在应用程序浏览器窗口关闭时也想实现后台推送通知,为了实现这一点,我正在使用service-worker和websocket,无法在serviceworker文件中使用websocket。
// 在 serviceworker.js 文件中
const webSocket = new WebSocket(`ws://local_host/socket`);
console.log(webSocket);
//出现以下错误
Uncaught DOMException: Failed to construct 'WebSocket': The
subprotocol '[object Object]' is invalid.
请帮忙解决这个问题。
Service Workers 不支持 Websocket。
推送通知应使用 Web Push 来实现。 https://developers.google.com/web/fundamentals/push-notifications/
Service Workers 必须在安全上下文 (https) 中运行。在安全上下文中,只能使用具有安全协议的 WebSocket (wss)。
这段代码在 Chrome + Firefox 的 Service Worker 中对我来说工作得很好:
let socket = new WebSocket(`${location.protocol === 'https:' ? 'wss:' : 'ws:'}//${location.hostname}/websocket`);
socket.onmessage = function(event) {
let json = JSON.parse(event.data);
self.registration.showNotification("Notification from WebSocket", {
"body": json.message,
"icon": "push_icon.png",
"vibrate": [200, 100, 200, 100, 200, 100, 200],
"tag": "websocket-sample",
});
};
请注意,在网站在用户交互事件中请求此权限后,最终用户必须首先授予从常规网站发送通知的权限。
但是,对于互联网上的网站,定期推送通知是更好的方法。